《PHP应用:微信网页授权(OAuth2.0) PHP 源码简单实现》要点:
本文介绍了PHP应用:微信网页授权(OAuth2.0) PHP 源码简单实现,希望对您有用。如果有疑问,可以联系我们。
提要: 1. 建议对OAuth2.0协议做一个学习.
2. 微信官方文档和微信官网工具要得到充分利用.
比较简单,直接帖源代码了.其中“xxxxxxxxxx”部分,是需要依据自己环境做替换的
PHP教程
/**
* OAuth2.0微信授权登录实现
*
* @author zzy
* @文件名:GetWxUserInfo.php
*/
// 回调地址
$url = urlencode("http://www.xxxxxxxxx.com/GetWxUserInfo.php");
// 公众号的id和secret
$appid = 'xxxxxxxxx';
$appsecret = 'xxxxxxxxx';
session_start();
// 获取code码,用于和微信服务器申请token. 注:依据OAuth2.0要求,此处授权登录需要用户端操作
if(!isset($_GET['code']) && !isset($_SESSION['code'])){
echo
授权';
exit;
}
// 依据code码去获取openid和access_token,自己的后台服务器直接向微信服务器申请即可
if (isset($_GET['code']) && !isset($_SESSION['token'])){
$_SESSION['code'] = $_GET['code'];
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid.
"&secret=".$appsecret."&code=".$_GET['code']."&grant_type=authorization_code";
$res = https_request($url);
$res=(json_decode($res, true));
$_SESSION['token'] = $res;
}
print_r($_SESSION);
// 依据申请到的access_token和openid,申请Userinfo信息.
if (isset($_SESSION['token']['access_token'])){
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$_SESSION['token']['access_token']."&openid=".$_SESSION['token']['openid']."&lang=zh_CN";
echo $url;
$res = https_request($url);
$res = json_decode($res, true);
$_SESSION['userinfo'] = $res;
}
print_r($_SESSION);
// cURL函数简单封装
function https_request($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
PHP教程得到正确结果如下:
PHP教程
Array
(
[code] => 041GZI4l0tvGHg10N75l05FQ4l0GZI42
[token] => Array
(
[access_token] => TWo6w5QMpzTZibu3FPh2k4EdC5bllp4sGeQkC4NbZtj-zti-ctZj1SrrNL1qGCf2lB1-6o3N7kh2bcxl5bxtQqJEGk1cq12l8CzF40R9XvA
[expires_in] => 7200
[refresh_token] => Iz3olCrkqPBOJvSSH2bOKvA09Sjvsp1c8Ltm7MvxxPfQXSbvI_WoVmzhjqASzwlMa7TAGgsg3mIJmaHjL7jrJHDqUF1jKbhd6GNDnLtXq0U
[openid] => ota_XwQ4r_5nioVmshQ
[scope] => snsapi_userinfo
)
[userinfo] => Array
(
[openid] => ota_XwQ4r_5nioVmshQq
[nickname] => 野狐
[sex] => 1
[language] => zh_CN
[city] => 杭州
[province] => 浙江
[country] => 中国
[headimgurl] => http://wx.qlogo.cn/mmopen/PiajxSqBRaELwee7rhrt2ibnkC1MEnu04WiaWrw9FkuPBbGOgnrMbynNoEuxicgXOetW5VqQbTrS4fZDXNvAWsz6GQ/0
[privilege] => Array
(
)
)
)
PHP教程以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持维易PHP.