1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > php微信网页授权登录代码 php微信网页授权代码(获取用户信息)

php微信网页授权登录代码 php微信网页授权代码(获取用户信息)

时间:2022-01-15 14:00:37

相关推荐

php微信网页授权登录代码 php微信网页授权代码(获取用户信息)

1.填写授权回调页面的域名 (注意只有服务号才可以页面授权)

登录公众平台-->开发者中心-->接口权限表

2.代码如下

scope为snsapi_base 那么用户必须是关注了公众号才能取得信息

index.php

//scope=snsapi_base 实例

$appid='你的AppId';

$redirect_uri = urlencode ( 'http://你的域名/getUserInfo.php' );

$url ="https://open./connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect";

header("Location:".$url);

getUserInfo.php

$appid = "你的AppId";

$secret = "你的AppSecret";

$code = $_GET["code"];

//第一步:取全局access_token

$url = "https://api./cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";

$token = getJson($url);

//第二步:取得openid

$oauth2Url = "https://api./sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";

$oauth2 = getJson($oauth2Url);

//第三步:根据全局access_token和openid查询用户信息

$access_token = $token["access_token"];

$openid = $oauth2['openid'];

$get_user_info_url = "https://api./cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";

$userinfo = getJson($get_user_info_url);

//打印用户信息

print_r($userinfo);

function getJson($url){

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$output = curl_exec($ch);

curl_close($ch);

return json_decode($output, true);

}

scope为snsapi_userinfo 用户不用关注公众号,也能取到信息,但是会有一个界面让用户去点击确认

index.php

$appid='你的AppId';

$redirect_uri = urlencode ( 'http://你的域名/getUserInfo.php' );

$url ="https://open./connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";

header("Location:".$url);

getUserInfo.php

$appid = "你的AppId";

$secret = "你的AppSecret";

$code = $_GET["code"];

//第一步:取得openid

$oauth2Url = "https://api./sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";

$oauth2 = getJson($oauth2Url);

//第二步:根据全局access_token和openid查询用户信息

$access_token = $oauth2["access_token"];

$openid = $oauth2['openid'];

$get_user_info_url = "https://api./cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";

$userinfo = getJson($get_user_info_url);

//打印用户信息

print_r($userinfo);

function getJson($url){

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$output = curl_exec($ch);

curl_close($ch);

return json_decode($output, true);

}

标签: 微信

顶一下

(0)

0%

踩一下

(0)

0%

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。