CODING
<?php /** * 微信接口获取/code/access_token/userinfo测试 * 1、引导用户进入授权页面同意授权,获取code * 2、通过code换取网页授权access_token,openid(与基础支持中的access_token不同) * 3、通过网页授权access_token和openid获取用户基本信息userinfo(支持UnionID机制) */ $appid = "wxb0ecfdea8055XXXX"; $secret = "102c519025101e19d74fa4c884b4XXXX"; $redirect_uri = "http://m.XXXX.com/xxxx.php"; $scope = "snsapi_base"; /*1、引导用户进入授权页面同意授权,获取code*/ /*code <= appid,redirect_uri[与后台设置需要一致],scope[snsapi_base]*/ $url_code = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=$scope&state=1#wechat_redirect"; if(empty($_GET['code'])){ //跳转到$url_code,会带一个code参数跳转回来 header("Location:$url_code"); }else{ $code = $_GET['code']; } /*2、通过code换取网页授权access_token,openid(与基础支持中的access_token不同)*/ /*access_token,openid <= appid,secret,code*/ $url_access_token = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code"; $json_access_token = file_get_contents($url_access_token); $arr_access_token = json_decode($json_access_token,TRUE); $access_token = $arr_access_token['access_token']; $openid = $arr_access_token['openid']; /*3、通过网页授权access_token和openid获取用户基本信息userinfo(支持UnionID机制)*/ /*userinfo <= access_token,openid*/ $url_userinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN"; $json_userinfo = file_get_contents($url_userinfo); $arr_userinfo = json_decode($json_userinfo,TRUE); /* arr_userinfo返回值: ["openid"]=>"oy3SMtwGXXXXnuLr7hr2l4" ["nickname"]=>"天天天晴_2014" ["sex"]=>int(1) ["language"]=>"zh_CN" ["city"]=>"东莞" ["province"]=>"广东" ["country"]=>"中国" ["headimgurl"]=>"http://wx.qlogo.cn/mmopen/SicNOemw9NjtgucsSTVDia1ktXXXX0qvibu057GkvUtFThKAKzb9zgYzOXQlNcD4ZTBCvGXXcibrehSEiceNWwicNJEXXrfrJicVg/0" ["privilege"]=>array(0) {} */ ?>
参考:
微信_公众平台开发者文档:http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html
原文地址:http://blog.csdn.net/amqvje/article/details/45069093