思路:
1、引导用户进入授权页面同意授权,获取code
2、通过code换取网页授权access_token(与基础支持中的access_token不同)
3、如果需要,开发者可以刷新网页授权access_token,避免过期
4、通过网页授权access_token和openid获取用户基本信息(支持UnionID机制) 测试代码:
1.微信访问此文件;
$APPID='微信公众号的appid';
$REDIRECT_URI='http://www.test.net/callback.php';
$scope='snsapi_base';
//$scope='snsapi_userinfo';//需要授权
$url='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$APPID.'&redirect_uri='.urlencode($REDIRECT_URI).'&response_type=code&scope='.$scope.'&state=123#wechat_redirect';
header("Location:".$url);
?>
2.在此回调文件中获取用户信息;
//http://www.test.net/callback.php
$appid = "微信公众号的appid";
$secret = "微信公众号的appsecret";
$code = $_GET["code"];
$get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
$json=json_decode(file_get_contents("$get_token_url"));
$access_token = $json->access_token;
$openid = $json->openid;
$get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&;
$userInfo=json_decode(file_get_contents("$get_user_info_url"));
//$_SESSION['user'] = $user_obj;
print_r($userInfo->openid);
?>
注:
file_get_contents函数需要在php.ini文件中启用,方法如下:
在php.ini中找到并修改
extension=php_openssl.dll
allow_url_include = On