微信公众号实现静默登陆与非静默登陆
- 非静默登陆
(1)需要引导用户点击
”https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=$url&response_type=code&scope=snsapi_userinfo#wechat_redirect“
参数说明
$appid 为 公众号appID
$url为授权后跳转地址(登陆一定会发生跳转)
(2)跳转后可以获取code参数,用get方法访问”https://api.weixin.qq.com/sns/oauth2/access_token?appid=&secret=$appsecret&code=$code&grant_type=authorization_code“
参数说明
$appsecret 为 公众号AppSecret
$code为刚获取的code
到这里可以获取用户openid,用户对公众号的唯一openid
html代码
<div id="wechatlogin">
<span >微信授权登陆</span>
</div>
<!--js代码-->
<script type="text/javascript">
$("#wechatlogin").click(function(){
window.location.href=encodeURI('{!!$url!!}'); /*(第一步拼接出来的url)*/
});
</script>
跳转后php代码
function logind(Request $request){
//跳转后获取的code
$code = $request->all()['code'];
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=";
$url .=$this->appid;
$url .="&secret=";
$url .=$this->appsecret;
$url .="&code=";
$url .=$code;
$url .="&grant_type=authorization_code";
$resultopenid = json_decode($this->https_request($url));
//唯一标识openid;
$openid = $resultopenid->openid;
//如果要获取用户详细信息需要拿access_token;
$access_token = $resultopenid->access_token;
如果需要获取用户详细信息
可用get访问“https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN”
$getinfourl = "https://api.weixin.qq.com/sns/userinfo?access_token=";
$getinfourl .= $access_token;
$getinfourl .= "&openid=";
$getinfourl .= $openid;
$getinfourl .= "&lang=zh_CN";
$html = json_decode($this->https_request_get($getinfourl));
- 静默登陆
(1)访问“https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=$url&response_type=code&scope=snsapi_base#wechat_redirect”
(2)跳转后可以获取code参数,用get方法访问”https://api.weixin.qq.com/sns/oauth2/access_token?appid=&secret=$appsecret&code=$code&grant_type=authorization_code“
(3)得到opendid
html代码
<script type="text/javascript">
window.location.href=encodeURI('{!!$wechaturl!!}');
</script>
php代码
$code = $request->all()['code'];
$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=";
$url .=$this->appid;
$url .="&secret=";
$url .=$this->appsecret;
$url .="&code=";
$url .=$code;
$url .="&grant_type=authorization_code";
$resultopenid = json_decode($this->https_request($url));
$access_token = $resultopenid->access_token;
$openid = $resultopenid->openid;