1.我们首先在公众测试号那配置授权回调域名(注意不加http和Https):
2.获取code
在控制器写入以下代码:
public function index(){ $appid="wx4ff531ee8a470861"; $rediret_url=urlencode('http://wyzdjg.top/vote/index.php/home/index/getcode'); // $rediret_url=urlencode('http://www.baidu.com'); $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$rediret_url&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"; header("location:".$url); }
public function getcode(){ $code=$_GET['code']; $json=$this->access_token($code); // echo $json; $arr=json_decode($json,true); $arr=array_change_key_case($arr,CASE_LOWER); if(isset($arr['access_token'])&& isset($arr['openid'])){ $this->userinfo($arr['access_token'],$arr['openid']); }else{ echo "获取access_token出错".$json; } }
3.获取网页授权的access_toekn:
public function access_token($code){ $appid="wx4ff531ee8a470861"; $secret="2ec9b2f1a1f67b8743d23f9fc70c1c97"; $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code"; $ret=https_request($url); return $ret; }