During the configuration process of the public account, many developers will add HTML5 pages to the menu, sometimes in The page needs to access the user information of the page. At this time, the web page authorization is required to obtain the user’s basic information
Bangkejia reminds everyone: the content introduced in this article is based on the yii2.0 framework
1. Set authorization callback domain name: Development ---> Interface permissions
Find "Web page authorization to obtain basic user information", click the corresponding "Modify" at the end, and fill in the authorization callback domain name in the response position of the pop-up box. The domain name here does not need to add http:// (about the web page authorization callback domain name) For detailed instructions, please refer to the public platform developer documentation)
2. Obtain authorization
About OAuth2.0 bloggers refer to the blog post of Fangbei Studio http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html (PS: Fangbei is a WeChat development master, among whom The content of WeChat development is relatively detailed, and it is recommended to refer to it), which analyzes the relevant content of WeChat official documents in detail, and also provides more detailed ideas and solutions for obtaining authorization.
In fact, the key to obtaining user information is to obtain the user's openid. The blogger wants to realize that users can automatically authorize themselves by clicking on the official account menu to open the page, so as to perform database operations on the user, so there are two ways:
(1) Use the custom menu to request authorization page
I will write a separate blog post after the custom menu. Here I will briefly describe authorization through the custom menu. This method requires advanced interface permissions and is limited to users who follow the official account and enter the page directly from the menu.
$menu = '{ "button":[ { "type": "view", "name": "商城", "url": "https://open.weixin.qq.com/connect/oauth/authorize?appid=xxx&redirect_uri=http://tx.heivr.com/index.php&response_type=code&scope=snsapi_base&state=#wechat_redirect" }, { "name":"快递服务", "sub_button":[ { "type":"click", "name":"发快递", "key":"express" }, { "type":"click", "name":"快递查询", "key":"ww" } ] }, ] }';
For views that require authorization, directly fill in the authorization request address provided by WeChat at the url, where:
•appid: Fill in the AppID in the basic configuration of WeChat public platform;
•redirect_uri: Fill in the address of the page that will jump after authorization is completed, that is, your own html5 page;
•state: parameters for jumping to the callback page;
•response_type: Two scopes for web page authorization. The official WeChat documentation explains as follows:
1. Web page authorization initiated with snsapi_base as the scope is used to obtain the openid of the user who enters the page, and is authorized silently and automatically jumps to the callback page. What users perceive is that they directly enter the callback page (often a business page)
2. Web page authorization initiated with snsapi_userinfo as the scope is used to obtain the user's basic information. However, this kind of authorization requires the user to manually agree, and since the user has agreed, there is no need to pay attention, and the user's basic information can be obtained after authorization.
According to this method, click "Mall" to receive the returned openid, and then proceed to the next step of obtaining user information.
(2) Use JS to automatically request the authorization page
This method is relatively clumsy and the steps are slightly complicated. However, there is currently no simplified method that can solve the needs. In addition, due to page jumps, the time to access the page will increase in most cases, but compared to the previous method, This method can obtain basic information about non-following users. Some programs may involve page sharing. The program does not force following, but other users who enter the page directly through sharing also need to record user information. In this case, you can consider this method. (The code bloggers related to WeChat development are encapsulated into tool calls. The used parts are posted here first. After the arrangement is completed, they will all be posted with download links)
The idea of this method is: js request link to get code ---> Use code in exchange for openid ---> Get basic user information
a. Edit configuration
In order to facilitate the writing of some WeChat parameters used in a separate class, it is convenient to modify, add and call
<?php namespace common\tools\wechat; /** * 微信请求相关配置类库 */ class ConfigTool { /** * 微信配置参数 * @return array 配置参数 */ public function setConfig() { // 用于验证微信接口配置信息的Token,可以任意填写 $config['token'] = '自己的token'; // appID $config['appid'] = '自己的appid'; // appSecret $config['secret'] = '自己的secret'; // 回调链接地址 $config['redirect_uri'] = 'http://tx.heivr.com/index.php?'; // 是否以 HTTPS 安全协议访问接口 $config['https_request'] = false; // 授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid), // snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且, // 即使在未关注的情况下,只要用户授权,也能获取其信息) $config['scope'] = 'snsapi_userinfo'; // 语言 $config['lang'] = 'zh_CN'; // zh_CN 简体,zh_TW 繁体,en 英语 // 微信公众账户授权地址 $config['mp_authorize_url'] = 'https://api.weixin.qq.com/cgi-bin/token'; // 微信公众账户js临时票据地址 $config['jsapi_ticket_url'] = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'; // 授权地址 $config['authorize_url'] = 'https://open.weixin.qq.com/connect/oauth/authorize'; // 获取access token 的地址 $config['access_token_url'] = 'https://api.weixin.qq.com/sns/oauth/access_token'; // 刷新 token 的地址 $config['refresh_token_url'] = 'https://api.weixin.qq.com/sns/oauth/refresh_token'; // 获取用户信息地址 $config['userinfo_url'] = 'https://api.weixin.qq.com/sns/userinfo'; // 验证access token $config['valid_token_url'] = 'https://api.weixin.qq.com/sns/auth'; // 上传临时素材地址 $config['media_temp_upload_url'] = 'https://api.weixin.qq.com/cgi-bin/media/upload?'; // 上传永久素材地址 $config['media_forever_upload_url'] = 'https://api.weixin.qq.com/cgi-bin/material/add_material?'; return $config; } }
b. https request tool
<?php namespace common\tools; /** * https请求相关类库 */ class HttpsTool { const TIMEOUT = ; // 设置超时时间 private $ch; // curl对象 /** * 发送curl请求,并获取请求结果 * @param string 请求地址 * @param array 如果是post请求则需要传入请求参数 * @param string 请求方法,get 或者 post, 默认为get * @param bool 是否以https协议请求 */ public function send_request($requests, $params = null, $method = 'get', $https = true) { // 以get方式提交 if ($method == 'get') { if($params){ $request = $requests . $this->create_url($params); }else{ $request = $requests; } }else{ $request = $requests; } $this->ch = curl_init($request); curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, );// 设置不显示结果,储存入变量 curl_setopt($this->ch, CURLOPT_TIMEOUT, self::TIMEOUT); // 设置超时限制防止死循环 // 判断是否以https方式访问 if ($https) { curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, ); // 对认证证书来源的检查 curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, ); // 从证书中检查SSL加密算法是否存在 } if ($method == 'post') { // 以post方式提交 //curl_setopt($this->ch, CURLOPT_SAFE_UPLOAD, false); //php .文件上传必加内容,.不需要 curl_setopt($this->ch, CURLOPT_POST, ); // 发送一个常规的Post请求 curl_setopt($this->ch, CURLOPT_POSTFIELDS, $params); // Post提交的数据包 curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, ); } $tmpInfo = curl_exec($this->ch); // 执行操作 if (curl_errno($this->ch)) { echo 'Errno:'.curl_error($this->ch);//捕抓异常 } curl_close($this->ch); // 关闭CURL会话 //var_dump($tmpInfo);exit; return $tmpInfo; // 返回数据 } /** * 生成url */ public function create_url($data) { $temp = '?'; foreach ($data as $key => $item) { $temp = $temp . $key . '=' . $item . '&'; } return substr($temp, , -); } }
Regarding curl_setopt($this->ch, CURLOPT_SAFE_UPLOAD, false), the sad history of its appearance will be described in detail in the WeChat image resource upload blog post. It will not be used here for the time being and will not be explained
c. Authorization base class
<?php namespace common\tools\wechat; use common\tools\wechat\ConfigTool; use common\tools\HttpsTool; /** * Weixin_oauth 类库 */ class OauthTool { public $conf; public function __construct(){ $re = new ConfigTool; $this->conf = $re->setConfig(); } /** * 生成用户授权的地址 * @param string 自定义需要保持的信息 * @param sting 请求的路由 * @param bool 是否是通过公众平台方式认真 */ public function authorize_addr($route, $state='', $mp=false) { if ($mp) { $data = [ 'appid' => $this->conf['appid'], 'secret' => $this->conf['token'], 'grant_type' => 'client_credential' ]; $url = $this->conf['mp_authorize_url']; } else { $data = [ 'appid' => $this->conf['appid'], //公众号唯一标识 'redirect_uri' => urlencode($this->conf['redirect_uri'] . $route), //授权后重定向的回调链接地址 'response_type' => 'code', //返回类型,此处填写code 'scope'=>$this->conf['scope'], //应用授权作用域 'state'=>$state, //重定向后带上state参数,开发者可以填写任意参数 '#wechat_redirect'=>'' //直接在微信打开链接,可不填,做页面重定向时必须带此参数 ]; $url = $this->conf['authorize_url']; } $send = new HttpsTool; //var_dump($url . $send->create_url($data));exit; return $url . $send->create_url($data); } /** * 获取 access token * @param string 用于换取access token的code,微信提供 */ public function access_token($code) { $data = [ 'appid' => $this->conf['appid'], 'secret' => $this->conf['secret'], 'code' => $code, 'grant_type' => 'authorization_code' ]; // 生成授权url $url = $this->conf['access_token_url']; $send = new HttpsTool; return $send->send_request($url, $data); } /** * 获取用户信息 * @param string access token * @param string 用户的open id */ public function userinfo($token, $openid) { $data = [ 'access_token' => $token, 'openid' => $openid, 'lang' => $this->conf['lang'] ]; // 生成授权url $url = $this->conf['userinfo_url']; $send = new HttpsTool; return $send->send_request($url, $data); } }
d. Authorization base class call and user data processing (user data is stored or updated before controller call)
<?php namespace wechat\controllers\classes; use common\tools\wechat\OauthTool; use common\models\User; use common\tools\EmojiTool; /** * 微信用户基本信息获取 */ class UserinfoClass { /** * 用户授权并获取code * @return string 用户code */ public function getCode($route, $state){ $re = new OauthTool; $request = $re->authorize_addr($route, $state); $code = isset($_GET['code']) ? $_GET['code'] : ''; return [$request,$code]; } /** * 获取用户信息并写入数据库(之后加参数传给code) */ public function info($code) { $re = new OauthTool; //获取access token $access = $re->access_token($code); $token = json_decode($access,true); //header("Content-type: text/html; charset=gbk"); //获取用户信息 if(count($token) != ) { $response = $re->userinfo($token['access_token'], $token['openid']); $user = json_decode($response,true); //用户昵称转换 //$user['nickname'] = EmojiTool::emoji_trans($user['nickname']); if($model = User::findOne(['openid' => $user['openid'] ])) { //用户已存在更新数据 $model->attributes = $user; $model->modify_time = time(); $model->save(false); }else{ //用户不存在写入 $model = new User; $model->attributes = $user; $model->create_time = time(); $model->save(false); } } return isset($model->id) ? $model->id : ''; } }
e. Controller call (only one of the methods is posted here)
/** * 产品列表 * @return object 所有可用产品信息 */ public function actionIndex(){ //判断页面是否自动刷新 if(isset($_GET['state'])) { $refresh = ; }else{ $refresh = ; } //获取用户code $user = new UserinfoClass; $request = $user->getCode('r=store/index', ); //该用户userid $userid = $user->info($request[]); $model = new Product; $list = $model->find()->where(['status' => ])->all(); return $this->render('index',['list' => $list, 'refresh' => $refresh, 'userid' => $userid, 'request' => $request]); }
The program requires the user to open the product list to obtain user information and store it in the database. Several variables are designed with the following functions:
$refresh: Determine whether the page is refreshed. Since the page is opened for the first time without oauth verification, verification is automatically requested to avoid repeated refreshes. Here, the state parameter of the callback is used as the basis for judgment and state=1 (if there are specific parameters required, you can Assign state to the required value);
$request: is the verification request address
f. View automatic refresh
Just add the following js code to the view
<script type="text/javascript"> //自动请求获取code $(function(){ var refresh = <?= $refresh; ?>; var request = '<?= $request[]; ?>'; if(refresh == ){ console.log(); location = request; } }); </script>
以上内容给大家介绍了微信开发之网页授权获取用户信息(二)的全部叙述,希望本文分享能够给大家带来帮助。