Access_token and log for WeChat public platform development

Source: Internet
Author: User
This article describes how to develop access_token, log 1, and access_token on the public platform.

1) two types of access_token: webpage authorization access_token and common access_token

1. webpage authorization is implemented through the OAuth2.0 mechanism. after a user authorizes a public account, the public account can obtain a webpage-authorized unique interface call credential (webpage-authorized access_token ), you can use the webpage-authorized access_token to call the authorized interface, for example, to obtain basic user information.


2. for other interfaces, you need to call the common access_token obtained through the "get access_token" interface in the basic support. Access_token is the globally unique ticket of the public account. The validity period of access_token is currently 2 hours. it needs to be refreshed regularly. repeated acquisition will invalidate the last access_token obtained.

2) obtain access_token respectively.

1. webpage authorization: Click to view webpage authorization to obtain the user's basic information document. you can view this document,

You can see that the code is exchanged for the webpage authorization access_token, and this code is obtained through an authorization link, and then obtained according to the request in the document, for specific link addresses and parameters, refer to the documentation.

/*** Create a service url that requires OAuth2.0 authentication * @ param $ url the url that the service number needs to be authenticated to access * @ param $ scope string snsapi_userinfo | snsapi_base * snsapi_userinfo can be obtained user information * snsapi_base can be used to obtain the openid * @ param string $ state custom state value * the from_weixin convention indicates that the authentication is passed, generally, you do not need to change it easily * @ return string returns the authentication url address */public function createAuthUrl ($ url, $ scope = 'snsapi _ base', $ state = 'from _ weixin ') {$ url = strval ($ url); $ authUrl =' https://open.weixin.qq.com/connect/oauth2/authorize ';/*** There is a big pitfall here, do not disturb the order of param * otherwise the authentication interface will display a white screen */$ param = array ('appid '=> $ this-> appid, 'redirect _ url' => urlencode ($ url), 'response _ type' => 'code', 'scope '=> $ scope, 'state' => $ state); $ seg = array (); foreach ($ param as $ k => $ v) {$ seg [] = "{$ k} = {$ v}";} return $ authUrl. '? '. Join (' & ', $ seg).' # wechat_redirect ';}

2. Common: Click to view the access token document and obtain it using three parameters.

Note that the token obtained is time-sensitive and valid for 2 hours. Therefore, I will save it in MongoDB and check whether the token has timed out in the database first, if not, you can directly retrieve data from the database to reduce unnecessary requests.

II. push logs

In the interaction with, a lot of log information is generated, and these logs are often analyzed during development. here I save the logs in MongoDB. In MongoDB, data of any structure can be stored in a document. Unlike MySQL, the field name must be defined. I often put various structures in a document during debugging.

On the entry page, that is, the URL (server address) mentioned above, the log storage logic is implemented here. The logic includes pushing a message when paying attention, scanning and following the QR code, clicking a menu to generate an event, and clicking a menu hyperlink.

The log structure is as follows:

1. the code includes the signature verification logic.

2. get the request data through file_get_contents ('php: // input'), which is the following getRawMsg method.

3. Add push logs directly to MongoDB.

4. the SimpleXMLElement object of the received request is the following parseMsg method.

5. handleEventMsg is processing various situations.

/*** Public account entry */public function actionPortal () {$ weixin = new Weixin (); // signature verification logic // if ($ weixin-> checkSignature ()) {// echo $ _ GET ['echostr']; //} // exit; // read original request data $ msg = $ weixin-> getRawMsg (); // push logs $ pushlog = new WeixinPushLog (); $ pushlog-> logWeixinPush ($ msg); $ msgObj = $ weixin-> parseMsg ($ msg ); if ($ msgObj = false |! Is_object ($ msgObj) {exit;} switch ($ msgObj-> MsgType) {case 'event': // receives event messages $ this-> handleEventMsg ($ msgObj ); break; default: // todo break ;}}

Public function getRawMsg () {return file_get_contents ('php: // input ');} /*** parse the received message * @ param string $ msg Message body * @ return bool | SimpleXMLElement */public function parseMsg ($ msg = '') {if (! $ Msg | empty ($ msg) {return false;} $ msgObj = simplexml_load_string ($ msg, 'simplexmlelement', LIBXML_NOCDATA ); if ($ msgObj = false |! ($ MsgObj instanceof \ SimpleXMLElement) {return false;} return $ msgObj ;}

6. if you want to push messages, add the die method

7. the following code only lists two types of events: Subscription and click events.

8. createRawTuWenMsg is concatenating XML. Click to view the template message interface.

Private function handleEventMsg ($ msgObj) {$ weixin = new Weixin (); $ openId = $ msgObj-> FromUserName; $ fromUserName = $ msgObj-> ToUserName; // not followed, push if ($ msgObj-> Event = 'Subscribe ') {$ pushData ['picurl'] = 'http: // mmbiz.qpic.cn/'; $ pushData ['title'] = 'Genetic testing, taking you to explore the mysteries of life '; $ pushData ['description'] = 'Why do different people look different in height, weight, skin color, and shape? But is it often similar to your parents? '; $ PushData ['URL'] = 'http: // mp.weixin.qq.com'; $ msg = $ weixin-> createRawTuWenMsg ($ fromUserName, $ openId, array ($ pushData )); die ($ msg);} elseif ($ msgObj-> Event = 'click') {// die ($ msg );}}

public function createRawTuWenMsg($fromUserName, $toUserName, $items = array())    {        if (!is_array($items)) {            return '';        }        $count = count($items);        $its = '';        foreach ($items as $item) {            $its .= <<
 
  <![CDATA[{$item['Title']}]]>
  {$item[&#39;Description&#39;]}
  
  {$item[&#39;PicUrl&#39;]}
  
  {$item[&#39;Url&#39;]}
  ITEMTPL;        }            $msg = <<
  
   {$toUserName}
   
   {$fromUserName}
   
   
    12345678
   
   news
   {$count}{$its}MSG;    return $msg;    }
  
 

Download demo:

Github address: https://github.com/pwstrick/weixin_demo

CSDN address: http://download.csdn.net/detail/loneleaf1/9045731

For more articles about access_token and log development on the public platform, refer to the PHP Chinese website!

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.