WeChat develops webpage authorization and obtains user information
introduce
There are two types of web page authorization, snsapi_base and snsapi_userinfo
. snsapi_base needs to follow the public account to obtain user information, but the user-insensitive
snsapi_userinfo does not need to follow the public account, but needs the user to confirm whether it is obtained.
Here, snsapi_userinfo is used as an example to obtain user information.
Create an access page index.php
<?php
//scope=snsapi_userinfo实例
$appid='微信appid';
$redirect_uri = urlencode ( 'http://存放地址/getUserInfo.php' );
$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
header("Location:".$url);
Create getUserInfo.php
<?php
$appid = "微信appid";
$secret = "微信secret";
$code = $_GET["code"];
//第一步:取得openid
$oauth2Url = "https://api.weixin.qq.com/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.weixin.qq.com/sns/userinfo?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);
}
access
Put the two files directly on the server and visit the index.php address
mistake
access_token illegal error
40001 No permission error
Carefully observe that the interface address referenced by the above code
is
https://api.weixin.qq.com/sns/userinfo
instead of
https://api.weixin.qq.com/cgi-bin/user/info
Get user information ideas
- Open the index.php page and jump to the getUserInfo.php page
- Obtain and store user information, and jump to the content page.
This is because the web page authorizes the acquisition of user information. The number of calls is 500 0000 times
Ideas for storing user information
A connection is established every time. This implementation is a short link, and the connection is closed when it is used up. Because mysql supports thousands of connections at the same time. And our connection has not reached a certain amount, there is no need to cache instances or establish long connections
WeChat information table structure
wx_OpenAndShare
id,openid,nickname,phone,open,share,project,time
wx_Information
id,openid,nickname,sex,province,city,country,headimgurl,language,phone,privilege,unionid,project,time