没时间多写,直接上代码。
第一步:获取code,其中的链接可以通过任何方式生成,也可以用微信公众号菜单
<?php
$APPID='wx7********6beb9db'; //填写高级调用功能的app id
$appsecret='ce03f4********09c3b80ae6f1c270d5'; //填写高级调用功能的密钥
$REDIRECT_URI='http://www.***.***:81/wechat/test/getcode_2.php';
$scope='snsapi_base';
//$scope='snsapi_userinfo';//需要授权
$state=1;
$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$APPID.'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
echo "url: ".$url;
header("Location:".$url);
?>
第二步: 按步骤获取:access_token、用户openid、用户基本信息
<?php
$APPID='wx7********6beb9db'; //填写高级调用功能的app id
$APPSECRET='ce03f4********09c3b80ae6f1c270d5'; //填写高级调用功能的密钥
$code = $_GET["code"];
//$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$APPID.'&secret='.$APPSECRET.'&code='.$code.'&grant_type=authorization_code';
$get_token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
$res = post($get_token_url);
$json_obj = json_decode($res,true);
//根据openid和access_token查询用户信息
$access_token = $json_obj['access_token'];
$get_openid_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$APPID.'&secret='.$APPSECRET.'&code='.$code.'&grant_type=authorization_code';
$res = post($get_openid_url);
$json_obj = json_decode($res,true);
$openid = $json_obj['openid'];
$get_user_base_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
$res = post($get_user_base_info_url);
$param = base64_encode($res);
$url = "http://218.***.***.10:8151/HiRunAdd.aspx?p=$param";
header("Location:".$url);
/*
$get_userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
$res = post($get_userinfo_url);
//解析json
$user_obj = json_decode($res,true);
$_SESSION['user'] = $user_obj;
print_r($user_obj);
echo "<br/>";
*/
function post($url){
echo "url: $url <br/>";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
$res = curl_exec($ch);
curl_close($ch);
echo "resp: $res <br/><br/>";
return $res;
}
?>
等到用户 基本信息格式如下:
{ "subscribe": 1, //是否已订阅 "openid": "oZA7CjhnBRG0SziGtMG216EK8L-g", //用户openid "nickname": "碎石头", //用户昵称 "sex": 1, //用户性别 "language": "zh_CN", //用户所用语言 "city": "所在城市", "province": "所在省份", "country": "中国", "headimgurl": "http://wx.qlogo.cn/mmopen/qE9MKluetOnjPBkUB95h3vo4HsStkrKEQtYVgD6iad1yib75TW92OHQyZYgIialhMQ2tKe4iaciakAv92o0U1Y9cPug/0", //用户头像地址 "subscribe_time": 1434330625, //用户订阅时间 "remark": "", //备注 "groupid": 0 //用户所在用户组,如果有分组的话 }