Home > Article > WeChat Applet > WeChat public platform development access_token, log
1) Two kinds of access_token, web page authorization access_token and ordinary access_token
1. WeChat web page authorization is implemented through the OAuth2.0 mechanism. When the user authorizes the official account Finally, the official account can obtain a web page authorization-specific interface call credential (web page authorization access_token). Through the web page authorization access_token, it can perform post-authorization interface calls, such as obtaining basic user information.
2. For other WeChat interfaces, you need to obtain the ordinary access_token call through the "Get access_token" interface in basic support. The access_token is the globally unique ticket for the official account. The validity period of the access_token is currently 2 hours and needs to be refreshed regularly. Repeated acquisition will cause the last access_token to become invalid.
2) Obtain access_token respectively
1, web page authorization: Click to view the web page authorization to obtain the user's basic information document. By viewing this document,
You can see that the code is exchanged for the web page authorization access_token, and this code is obtained through an authorization link on WeChat, and then obtained according to the request in the document. For the specific link address and parameters, please refer to the document.
/** * 创建一个需要通过微信的OAuth2.0认证的服务url * @param $url 服务号需要认证访问的url * @param $scope string snsapi_userinfo | snsapi_base * snsapi_userinfo 可以用来获取用户信息 * snsapi_base 可以用来获取openid * @param string $state 自定义状态值 * 此处约定为from_weixin代表是从微信认证过来,一般无需轻易变化 * @return string 返回认证url地址 */ public function createAuthUrl($url, $scope = 'snsapi_base', $state = 'from_weixin') { $url = strval($url); $authUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize'; /** * 此处有大坑,请不要打乱param的顺序 * 否则微信认证界面会出现白屏 */ $param = array( 'appid' => $this->appId, 'redirect_uri' => 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. Ordinary: Click to view the access token document, which is obtained through three parameters.
It should be noted here that the token obtained is time-sensitive, 2 hours, so I will save it in MongoDB and first compare it with the database to see if it has timed out. , if not, get it directly from the database to reduce unnecessary requests.
During the interaction with WeChat, a lot of log information will be generated, and it is often necessary to analyze these logs during development , here I save the logs in MongoDB. The convenience of MongoDB is that data of any structure can be placed in a document. Unlike MySQL, which requires well-defined field names, I often put various structures in a document when debugging.
In the entrance page of WeChat, which is the URL (server address) mentioned above, the logic of saving logs will be done here. The logic includes pushing a message when following, scanning the QR code to follow, clicking on a menu to generate an event, clicking on the hyperlink of the menu, etc.
The log structure is as follows:
1. The code includes signature verification logic
2. Through file_get_contents('php: //input') to obtain the request data, which is the getRawMsg method below
3. Insert the push log directly into MongoDB
4. The received request information SimpleXMLElement object is The following parseMsg method
5 and handleEventMsg handle various situations
/** * 微信公众号入口 */ public function actionPortal() { $weixin = new Weixin(); //签名验证逻辑 // if($weixin->checkSignature()){ // echo $_GET['echostr']; // } // exit; //读取原始请求数据 $msg = $weixin->getRawMsg(); //推送日志 $pushlog = new WeixinPushLog(); $pushlog->logWeixinPush($msg); $msgObj = $weixin->parseMsg($msg); if ($msgObj === false || !is_object($msgObj)) { exit; } switch ($msgObj->MsgType) { case 'event' : //接收事件消息 $this->handleEventMsg($msgObj); break; default : //todo break; } }
public function getRawMsg() { return file_get_contents('php://input'); } /** * 解析接收到的消息 * @param string $msg 消息体 * @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, the die method must be added
7. The following code only lists two event situations, one is subscription and the other is Click event
8, createRawTuWenMsg is splicing XML, click to view the template message interface.
private function handleEventMsg($msgObj) { $weixin = new Weixin(); $openId = $msgObj->FromUserName; $fromUserName = $msgObj->ToUserName; //未关注,关注后推送 if ($msgObj->Event == 'subscribe') { $pushData['PicUrl'] = 'http://mmbiz.qpic.cn/'; $pushData['Title'] = '基因检测,带你一起探索生命的奥妙 '; $pushData['Description'] = '为什么不同人在身高、体重、肤色和形状上长得不一样?但是往往又和自己的父母相似?'; $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 .= <<<ITEMTPL <item> <Title><![CDATA[{$item['Title']}]]></Title> <Description><![CDATA[{$item['Description']}]]></Description> <PicUrl><![CDATA[{$item['PicUrl']}]]></PicUrl> <Url><![CDATA[{$item['Url']}]]></Url> </item> ITEMTPL; } $msg = <<<MSG <xml> <ToUserName><![CDATA[{$toUserName}]]></ToUserName> <FromUserName><![CDATA[{$fromUserName}]]></FromUserName> <CreateTime>12345678</CreateTime> <MsgType><![CDATA[news]]></MsgType> <ArticleCount>{$count}</ArticleCount> <Articles> {$its} </Articles> </xml> MSG; return $msg; }
demo download:
github address: https://github.com/pwstrick/weixin_demo
CSDN address: http://download.csdn.net/detail/loneleaf1/9045731
For more articles related to WeChat public platform development access_token and logs, please pay attention to the PHP Chinese website!