不言不语

您现在的位置是: 首页 >  PHP

PHP

网站微信授权登录详细教程

2022-06-01PHP
网站通过接入微信登录功能,用户可使用微信帐号快速登录你的网站,降低注册门槛,提高用户留存,示例代码如下:

第一步:请求CODE


//配置
$AppID='wx427bd690bdd58f';
$AppSecret='d4624c36b6795d1d99dcf0547af544';
$callback='http://www.yanyublog.cn';	//回调地址

//微信登录
$state=md5(uniqid(rand(),TRUE));	//生成唯一随机串防CSRF攻击
$_SESSION["wx_state"]=$state;		//存到SESSION
$callback=urlencode($callback);
$wxurl="https://open.weixin.qq.com/connect/oauth2/authorize?appid={$AppID}&redirect_uri={$callback}&response_type=code&scope=snsapi_login&state={$state}#wechat_redirect";
header("Location: $wxurl");


第二步:通过code获取access_token


//配置
$AppID='wx427bd690bdd58f';
$AppSecret='d4624c36b6795d1d99dcf0547af544';

//得到 access_token 与 openid
$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$AppID.'&secret='.$AppSecret.'&code='.$_GET['code'].
'&grant_type=authorization_code';
$ch=curl_init();
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($ch,CURLOPT_URL,$url);
$json=curl_exec($ch);
curl_close($ch);
$arr=json_decode($json,1);


第三步:通过access_token调用接口

//得到用户资料
$url='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
$ch=curl_init();
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($ch,CURLOPT_URL,$url);
$json=curl_exec($ch);
curl_close($ch);
$arr=json_decode($json,1);


 


文章评论