12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- <?php
- namespace wx;
- class Base
- {
- /**
- * 获取普通token
- * @param $appid
- * @param $secret
- * @return mixed
- */
- public function getAccessToken($appid, $secret)
- {
- $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret.'';
- $res = $this->curl($url);
- $res = json_decode($res, true);
- if(isset($res['errcode'])){
- trace($res, 'error');
- return null;
- }
- return $res['access_token'];
- }
- /**
- * 请求接口
- * @param $url
- * @param null $data
- * @return mixed|null
- */
- protected function curl($url, $data=null)
- {
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-type: application/json; encoding=utf-8']);
- if (!empty($data)) {
- curl_setopt($curl, CURLOPT_POST, 1);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- }
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_HEADER, false);
-
- $data = curl_exec($curl);
- curl_close($curl);
- return $data;
- }
- /**
- * H5授权,code换accesstoken
- */
- public function getAccessTokenByCode($appid, $secret, $code)
- {
- $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
- $res = $this->curl($url);
- // 返回获取结果
- return json_decode($res, true);
- }
- /**
- * H5跳转获取code
- */
- public function redirectForCode($appid, $redirectUrl)
- {
- $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $appid . '&redirect_uri=' . urlencode($redirectUrl) . '&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
- header('location:' . $url);
- exit;
- }
- }
|