Website Authorization for micro-credit development Get user Information (ii) _php example

Source: Internet
Author: User
Tags curl oauth openid

In the public number configuration process, many developers will be in the menu to add HTML5 page, sometimes in the page needs to access the page's user information, this time requires the Web page authorization to obtain user basic information

The cloud-dwelling community reminds you that this article is about the YII2.0 framework based on

1, set the authorization callback domain name: Development---> Interface permissions

Find "website authorization to obtain user basic information", click on the corresponding "modified", in the frame response location to fill in the authorization callback domain name, where the domain name does not need to add http://(for Web page authorization callback domain name details can refer to the Public Platform developer documentation)


2. Obtain authorization

A reference to the OAuth2.0 blogger is the blog post of the square-times Studio http://www.cnblogs.com/txw1958/p/ Weixin71-oauth20.html (PS: Square Times is a micro-letter development of the Great God, which is the micro-letter development content is more detailed, recommended reference), which detailed analysis of the micro-letter official documents related content, but also provides more detailed ideas and programs to obtain authorization.

In fact, the key to getting user information is to get the user's OpenID. Bloggers want to achieve user click on the Public Number menu open page can be automatically authorized to do database operations for the user, so there are the following two ways:

(1) Request authorization page with custom menu

The custom menu will be followed by a separate blog post, and here is a brief summary of the authorization by customizing the menu, which requires advanced interface permissions, and is restricted to users who are concerned with public numbers to enter the page directly 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 ":" Express Service ",
" Sub_button ": [
{
] Type ': ' Click ',
' name ': ' Express ',
' key ': ' Express '
},
{
' type ': ' Click ',
' name ': ' Express Inquiry ',
"key": "WW"
}
]
},
]

The view that requires authorization is directly filled in at the URL by the address of the authorization request provided by the micro-letter, where:

AppID: Fill in the AppID of the basic configuration of the micro-trust public platform;
Redirect_uri: Fill in the page address after the authorization completes, namely own HTML5 page;
state: Jump to the callback page with the parameters;
Response_type: Two scopes for Web page authorization, as described in the micro-credit Official document:

1, the snsapi_base for the scope of the launch of the Web page authorization, is used to obtain access to the page of the user's OpenID, and is silent authorization and automatically jump to the callback page. What the user perceives is a direct entry into the callback page (often a business page)

2, the Snsapi_userinfo for the scope of the launch of the Web page authorization, is used to obtain the user's basic information. However, this authorization requires the user to manually agree, and because the user agreed, so no concern, you can obtain the user's basic information after authorization.
According to this method click on "Mall" can receive the return of OpenID, and then the next step to obtain user information.

(2) Use JS Automatic Request authorization page

This approach is relatively clumsy, the steps slightly complex, but currently can solve the requirements have not studied the simplification method, and because the page jump in most cases to access the page time will increase, but compared to the previous method, this method can obtain the basic information of the non-concern users. Some programs may involve the sharing of the page, the program is not mandatory attention, but other users through the sharing of direct access to the page also need to record user information, you can consider this method. (Micro-credit development-related code bloggers packaged into tool class calls, here first paste the use of the part, after finishing will be all posted and download link)

The idea of this method is: JS request link Get code---> Use code in exchange for OpenID---> get user basic information

A. Edit configuration

In order to facilitate the use of some of the micro-letter parameters to write a separate class, easy to modify add and call

<?php namespace Common\tools\wechat; /** * Micro-letter request-Related Configuration class Library */class Configtool {/** * micro-trust configuration parameters * @return Array configuration Parameters/Public function Setconfig () {//For authentication of micro-interface configuration information
Token, you can fill in $config [' Token '] = ' own Token ';
AppID $config [' appID '] = ' own AppID ';
Appsecret $config [' secret '] = ' own secret ';
Callback link address $config [' redirect_uri '] = ' http://tx.heivr.com/index.php? ';
Whether to access the interface with the HTTPS security protocol $config [' https_request '] = false; Authorization scope, snsapi_base (not eject authorization page, direct jump, can only get user OpenID),//Snsapi_userinfo (pop-up authorization page, can get nickname, sex, location via OpenID).
And,//even in the event of no concern, as long as the user authorized to obtain their information $config [' scope '] = ' snsapi_userinfo '; Language $config [' lang '] = ' zh_cn ';
ZH_CN Simplified, zh_tw traditional, en English//micro-trust public account authorized Address $config [' mp_authorize_url '] = ' https://api.weixin.qq.com/cgi-bin/token ';
Micro-Credit public account JS temporary bill address $config [' jsapi_ticket_url '] = ' https://api.weixin.qq.com/cgi-bin/ticket/getticket ';
The authorized address $config [' authorize_url '] = ' https://open.weixin.qq.com/connect/oauth/authorize '; Gets the address $config access token [' access_token_url '] = ' https://api.weixin.qQ.com/sns/oauth/access_token ';
Refresh token address $config [' refresh_token_url '] = ' https://api.weixin.qq.com/sns/oauth/refresh_token ';
Get the user information address $config [' userinfo_url '] = ' https://api.weixin.qq.com/sns/userinfo ';
Verify that access token $config [' valid_token_url '] = ' https://api.weixin.qq.com/sns/auth ';
Upload temporary material address $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

<?php namespace Common\tools; /** * HTTPS request-related class library */class Httpstool {const TIMEOUT =;//Set timeout time private $ch;//Curl Object/** * Send Curl request and GET request result * @param String Request Address * @param array if the POST request requires an incoming request parameter * @param string request method, get or post, default to get * @param bool is requested by HTTPS protocol/Publi C function Send_request ($requests, $params = null, $method = ' get ', $https = True) {//Get-way to submit if ($method = = ' Get ') {I F ($params) {$request = $requests. $this->create_url ($params); else{$request = $requests;}}
else{$request = $requests; $this->ch = Curl_init ($request); curl_setopt ($this->ch, Curlopt_returntransfer,)//setting does not display results, store into variable curl_setopt ($this->ch, curlopt_timeout, self :: TIMEOUT); Set a time-out limit to prevent dead loops//To determine whether to access the if ($https) {curl_setopt ($this->ch, Curlopt_ssl_verifypeer,) on an HTTPS basis;//Check the source of the certificate Curl_set Opt ($this->ch, Curlopt_ssl_verifyhost,); Check that the SSL encryption algorithm exists in the certificate ($method = = ' Post ') {//Post//curl_setopt ($this->ch, Curlopt_safe_upload, false);//ph P. File upload must add content,. No need for CURl_setopt ($this->ch, Curlopt_post,); Send a regular POST request curl_setopt ($this->ch, Curlopt_postfields, $params);
Post-Submitted packet curl_setopt ($this->ch, Curlopt_returntransfer,); } $tmpInfo = curl_exec ($this->ch); Execute action if (Curl_errno ($this->ch)) {echo ' errno: '. Curl_error ($this->ch);//Catch Exception} curl_close ($this->ch);
Closes Curl session//var_dump ($tmpInfo); exit; return $tmpInfo; Return Data}/** * Generate URL/Public function Create_url ($data) {$temp = '? '; foreach ($data as $key => $item) {$temp = $t Emp. $key. '=' . $item.
' & ';
Return substr ($temp,,-); }
}

About curl_setopt ($this->ch, Curlopt_safe_upload, false) will be in the micro-letter picture Resources upload Blog Details of its sad history, here for the time being not used, do not explain

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; the public Function __construct () {$re = new Configtool;
$this->conf = $re->setconfig (); /** * Generate user-Authorized address * @param string Customize the information that needs to be maintained * @param sting the requested route * @param BOOL is a serious/public function via a common platform Authoriz E_addr ($route, $state = ', $mp =false) {if ($MP) {$data = [' AppID ' => $this->conf[' AppID '], ' secret ' => $this-&G
t;conf[' token '], ' grant_type ' => ' client_credential '];
$url = $this->conf[' Mp_authorize_url ']; else {$data = [' AppID ' => $this->conf[' AppID '],//Public number Unique identification ' Redirect_uri ' => urlencode ($this->conf[' Redirec T_uri '].
$route),//Authorized redirect Callback link address ' response_type ' => ' code ',//return type, where code ' scope ' => $this->conf[' scope '],//Apply authorization scope
' State ' => $state,//redirect after the state parameter, developers can fill in any parameter ' #wechat_redirect ' => '//directly in the micro-letter open link, can not fill, do page redirection must take this parameter];
$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 in exchange for code in access token, micro-letter provides/public function Access_token ($code) {$data = [' App Id ' => $this->conf[' AppID '], ' secret ' => $this->conf[' secret '], ' code ' => $code, ' grant_type ' => ' Autho
Rization_code '];
Generate 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) {$dat
A = [' Access_token ' => $token, ' OpenID ' => $openid, ' lang ' => $this->conf[' Lang ']];
Generate authorization URL $url = $this->conf[' Userinfo_url '];
$send = new Httpstool;
Return $send->send_request ($url, $data); }
}

D. Authorization base class invocation and user data processing (to be saved or updated before the controller call)

<?php namespace Wechat\controllers\classes;
Use Common\tools\wechat\oauthtool;
Use Common\models\user;
Use Common\tools\emojitool; /** * Micro-Credit User basic information Access/class Userinfoclass {/** * user authorization and Get code * @return String user code */Public function GetCode ($route, $s Tate) {$re = new Oauthtool $request = $re->authorize_addr ($route, $state); $code = isset ($_get[' code ')? $_get[' Code '
] : '';
return [$request, $code]; /** * Get the user information and write to the database (after adding parameters to 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 "); Get user Information if (count ($token)!=) {$response = $re->userinfo ($token [' Access_token '], $token [' OpenID ']); $user = Json_dec
Ode ($response, True);
User Nickname conversion//$user [' nickname '] = Emojitool::emoji_trans ($user [' nickname ']); if ($model = User::findone ([' OpenID ' => $user [' OpenID ']]) {//user already has update data $model->attributes = $user; $model->mod
Ify_time = time (); $Model->save (FALSE); }else{//user does not exist write $model = new user; $model->attributes = $user; $model->create_time = time (); $model->save (False)
; } return Isset ($model->id)?
$model->id: ';  }
}

E. Controller invocation (only one of the methods is attached here)

/**
* Product List
* @return Object all available product information
/Public Function Actionindex () {
//To determine whether the page automatically refreshes
if (isset ($_get[' state ')) {
$refresh =;
} else{
$refresh =;
}
Gets the user code
$user = new Userinfoclass;
$request = $user->getcode (' R=store/index ',);
The user 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 ' => $re Quest]);
}

The program asks the user to open the product list namely obtains the user information and stores the database, in which several variables function is designed as follows:

$refresh: To determine whether the page is refreshed, because the first time the page is not OAuth validation, automatic request verification, avoid repeated refresh, here with the callback state parameter as the basis for judgment and set state=1 (if a specific parameter needs can be assigned to the state value);

$request: Is the authentication request address

F. Automatic View Refresh

Just add the following JS code to the view

<script type= "Text/javascript" >
//Automatic request Get code
$ (function () {
var refresh = <?= $refresh;?>;
var request = ' <?= $request [];?> ';
if (refresh = =) {
console.log ();
location = Request;
}
});
</script>

The above content to introduce the micro-letter development of the Web page authorization to obtain user information (ii) of the full account, I hope this article can help you to share.

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.