Web page authorization for WeChat development to obtain user information (2), user information _ PHP Tutorial

Source: Internet
Author: User
Tags oauth openid
Developer webpage authorization to obtain user information (2). user information. Developer webpage authorization to obtain user information (2). many developers add HTML5 pages to the menu during the public account configuration process, sometimes you need to access the page development page authorization on the page to obtain user information (2). user information

Many developers add HTML5 pages to the menu during the public account configuration process. sometimes, they need to access the user information on the page. in this case, they need webpage authorization to obtain basic user information.

Helper's house reminds you that the content described in this article is based on the yii2.0 framework.

1. set the authorization callback domain name: Developer ---> interface permission

Find "webpage authorization to obtain basic user information", click "modify" next to it, and fill in the authorization callback domain name in the response position in the pop-up box. http is not required for the domain name here: // (for details about the webpage authorization callback domain name, refer to the public platform developer documentation)


2. get authorization

On the OAuth2.0 blogger reference is Fang times studio blog http://www.cnblogs.com/txw1958/p/weixin71-oauth20.html (PS: Fang times is a great developer, the development content is more detailed, recommended reference ), the document details the relevant content of the official document and provides more detailed ideas and solutions for obtaining authorization.

In fact, the key to getting user information is to get the user's openid. If the user clicks the public account menu to open the page, the user can be automatically authorized to perform database operations on the user. There are two methods:

(1) request authorization page using custom menu

The custom menu will be followed by a separate blog post. here we will briefly describe how to authorize through the custom menu. this method requires advanced interface permissions, users who follow the public account can directly access the page from the menu.

$ Menu = '{"button": [{"type": "view", "name": "mall", "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 ":" courier service "," sub_button ": [{" type ":" click "," name ": "Courier", "key": "express" },{ "type": "click", "name": "Courier query", "key ": "ww"}]},]} ';

View to be authorized directly fill in the provided authorization request address in the url, where:

• Appid: Enter the AppID in the basic configuration of the public platform;
• Redirect_uri: enter the address of the page to jump to after authorization, that is, your html5 page;
• State: Jump to the callback page with parameters;
• Response_type: two scopes authorized by the webpage. the official documents are described as follows:

1. webpage authorization initiated with snsapi_base as scope is used to obtain the openid of the user entering the page, and is silently authorized and automatically redirected to the callback page. Users directly access the callback page (usually the business page)

2. webpage authorization initiated with snsapi_userinfo as scope is used to obtain basic user information. However, such authorization requires the user's manual consent, and the user's basic information can be obtained after authorization without concern.
Click "marketplace" in this method to receive the returned openid, and then obtain the user information in the next step.

(2) automatically request authorization page using JS

This method is relatively clumsy and the steps are slightly complicated. However, there is no simplified method to solve the problem, and the page access time will increase in most cases, however, compared with the previous method, this method can obtain basic information of non-followers. Some programs may involve page sharing, and the program does not force attention. However, when other users directly access the page through sharing, they also need to record user information. in this case, you can consider this method. (The development-related code blogger encapsulates the code into a tool class call. here we will post the part used first. after the compilation is completed, all the parts will be posted and the download link will be attached)

The idea of this method is: js request link get code ---> use code in exchange for openid ---> get basic user information

A. Edit the configuration

To facilitate writing some parameters used into a class separately, it is convenient to modify, add, and call

<? Phpnamespace common \ tools \ wechat;/*** request related configuration class library */class ConfigTool {/*** configuration parameter * @ return array configuration parameter */public function setConfig () {// Token used to verify the interface configuration information. you can enter $ config ['token'] = 'Your token' at will '; // appID $ config ['appid '] = 'Your appid'; // appSecret $ config ['secret'] = 'your own secret '; // callback link address $ config ['redirect _ uri '] =' http://tx.heivr.com/index.php ? '; // Whether to access the interface $ config ['https _ request'] = false; // authorization scope, snsapi_base, only user openid can be obtained), // snsapi_userinfo (the authorization page is displayed. you can obtain nickname, gender, and location through openid. In addition, // you can obtain the user's information even if you do not pay attention to it.) $ config ['extension'] = 'snsapi _ userinfo '; // Language $ config ['Lang '] = 'zh _ cn'; // zh_CN simplified, zh_TW traditional, en English // public account authorization address $ config ['MP _ authorize_url '] =' https://api.weixin.qq.com/cgi-bin/token '; // Public account js temporary ticket address $ config ['jsapi _ ticket_url'] =' https://api.weixin.qq.com/cgi-bin/ticket/getticket '; // Authorization address $ config ['authorize _ url'] =' https://open.weixin.qq.com/connect/oauth/authorize '; // Obtain the access token address $ config ['Access _ token_url'] =' https://api.weixin.qq.com/sns/oauth/access_token '; // Refresh the token address $ config ['refresh _ token_url'] =' https://api.weixin.qq.com/sns/oauth/refresh_token '; // Obtain the user information address $ config ['userinfo _ url'] =' https://api.weixin.qq.com/sns/userinfo '; // Verify access token $ config ['valid _ token_url'] =' https://api.weixin.qq.com/sns/auth '; // The address for uploading temporary Materials $ config ['media _ temp_upload_url'] =' https://api.weixin.qq.com/cgi-bin/media/upload ? '; // Upload permanent material address $ config ['media _ forever_upload_url'] =' https://api.weixin.qq.com/cgi-bin/material/add_material ? '; Return $ config ;}}

B. https request tool

<? Phpnamespace common \ tools;/*** https request-related class library */class HttpsTool {const TIMEOUT =; // Set the TIMEOUT value private $ ch; // curl object/*** sends a curl request, and get the request result * @ param string request address * @ param array if it is a post request, you need to input the request parameter * @ param string request method, get or post, the default value is get * @ param bool. whether to send https requests */public function send_request ($ requests, $ params = null, $ method = 'get', $ https = true) {// submit if ($ method = 'get') {if ($ params) {$ request = $ re Quests. $ this-> create_url ($ params);} else {$ request = $ requests ;} $ this-> ch = curl_init ($ request); curl_setopt ($ this-> ch, CURLOPT_RETURNTRANSFER,); // set not to display the result, store the variable curl_setopt ($ this-> ch, CURLOPT_TIMEOUT, self: TIMEOUT); // Set the TIMEOUT limit to prevent endless loops // determine whether to access if ($ https) in https mode) {curl_setopt ($ this-> ch, CURLOPT_SSL_VERIFYPEER,); // Check the certificate source curl_setopt ($ this-> ch, CURLOPT_SSL_VERIFYHOST ,); // Check from the certificate whether the SSL encryption algorithm exists} if ($ method = 'post') {// submit in post mode // curl_setopt ($ this-> ch, CURLOPT_SAFE_UPLOAD, false); // php. content required for file upload ,. no need for curl_setopt ($ this-> ch, CURLOPT_POST,); // send a regular Post request curl_setopt ($ this-> ch, CURLOPT_POSTFIELDS, $ params ); // curl_setopt ($ this-> ch, CURLOPT_RETURNTRANSFER,);} $ tmpInfo = curl_exec ($ this-> ch ); // execute the operation if (curl_errno ($ this-> ch) {echo 'errno :'. curl_error ($ This-> ch); // catch exceptions} curl_close ($ this-> ch); // Close the CURL session // var_dump ($ tmpInfo); exit; return $ tmpInfo; // return data}/*** generate url */public function create_url ($ data) {$ temp = '? '; Foreach ($ data as $ key => $ item) {$ temp = $ temp. $ key. '= '. $ item. '&';} return substr ($ temp ,,-);}}

For more information about curl_setopt ($ this-> ch, CURLOPT_SAFE_UPLOAD, false), we will detail the Heartbleed history in the image resource Upload blog. it is unavailable 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 library */class OauthTool {public $ conf; public function _ construct () {$ re = new ConfigTool; $ this-> conf = $ re-> setConfig ();} /*** generate the user-authorized address * @ param string custom information to be maintained * @ param sting route request * @ param bool whether the public platform is used seriously */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 '], // the public account uniquely identifies 'redirect _ Uris '=> urlencode ($ this-> conf ['redirect _ Uris']. $ route), // The callback link address for redirection after authorization 'response _ type' => 'code', // return type, enter the code 'scope '=> $ this-> conf ['scope'], // apply the authorization scope 'state' => $ state, // add the state parameter after redirection, developers can enter any parameter '# wechat_redirect' => '// directly open the link. this parameter is required for Page Redirection.] $ url = $ this-> conf ['authorize _ url'];} $ send = new HttpsTool; // var_dump ($ url. $ send-> create_url ($ data); exit; return $ url. $ send-> create_url ($ data);}/*** get access token * @ param string is used in exchange for the code of access token, providing */public function access_token ($ code) {$ data = ['appid '=> $ this-> conf ['appid'], 'secret' => $ this-> conf ['secret'], 'code' => $ code, 'Grant _ type' => 'authorization _ Code']; // Generate the authorization url $ url = $ this-> conf ['Access _ token_url ']; $ send = new HttpsTool; return $ send-> send_request ($ url, $ data);}/*** get user information * @ param string access token * @ param string user's open id */public function userinfo ($ token, $ openid) {$ data = ['Access _ token' => $ token, 'openid' => $ openid, 'Lang '=> $ this-> conf ['Lang']; // Generate the authorization url $ url = $ this-> conf ['userinfo _ url']; $ send = new HttpsTool; return $ send-> send_request ($ url, $ data );}}

D. authorize base-class calls and user data processing (store or update user data before controller calls)

<? Phpnamespace wechat \ controllers \ classes; use common \ tools \ wechat \ OauthTool; use common \ models \ User; use common \ tools \ EmojiTool; /*** obtain basic user information */class UserinfoClass {/*** authorize the user and obtain code * @ return string user code */public function getCode ($ route, $ state) {$ re = new OauthTool; $ request = $ re-> authorize_addr ($ route, $ state); $ code = isset ($ _ GET ['code'])? $ _ GET ['code']: ''; return [$ request, $ code] ;}/ *** GET user information and write it to the database (then add a parameter to the code) */public function info ($ code) {$ re = new OauthTool; // get access token $ access = $ re-> access_token ($ code ); $ token = json_decode ($ access, true); // header ("Content-type: text/html; charset = gbk "); // obtain user information if (count ($ token )! =) {$ Response = $ re-> userinfo ($ token ['Access _ token'], $ token ['openid']); $ user = json_decode ($ response, true); // user nickname conversion // $ user ['nickname'] = EmojiTool: emoji_trans ($ User ['nickname']); if ($ model = user :: findOne (['openid' => $ user ['openid']) {// the user already has updated data $ model-> attributes = $ user; $ model-> modify_time = time (); $ model-> save (false);} else {// The User does not exist and writes $ model = new User; $ model-> attributes = $ user; $ model-> Re Ate_time = time (); $ model-> save (false) ;}} return isset ($ model-> id )? $ Model-> id :'';}}

E. Controller call (only one method is attached here)

/*** Product list ** @ return object all available product information */public function actionIndex () {// Determine whether the page is automatically refreshed if (isset ($ _ GET ['state']) {$ refresh =;} else {$ refresh = ;} // obtain the user 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 to serve the following purposes:

$ Refresh: checks whether the page is refreshed. because the first time the page is opened, no oauth verification is performed, automatic verification is requested to avoid repeated refresh, here, the callback state parameter is used as the judgment basis and the state is set to 1 (if a specific parameter is required, the state can be assigned as the required value );

$ Request: The authentication request address.

F. View auto-refresh

You only need to add the following js code to the view.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.