Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Wechat developing QR Code with parameters

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Xiaobian to share with you Wechat development with parameters of the QR code example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article. Let's take a look at it!

1 access

First, enter the official account of Wechat-> basic configuration.

The following is the page of basic configuration. Enter the server address in URL, which is an interface that accepts Wechat push events. I developed a program using the thinkPHP framework to create a new class under the Action directory of one of the Module (Decoration), such as WechatAction.class.php, and a new public method in the Action, such as URLRedirect () Well, fill in the http://[IP]:[port]/index.php/Decoration/Wechat/UrlRedirect in this URL, and then fill in Token,Token at will. It doesn't matter whether you want to EncodingAESKey or not. Then click OK. Wechat will send a get request to this URL, which contains many parameters, most of which are for us to check whether the visit was requested by Wechat server. I have not verified it myself. His request is that if we check successfully, we will return a parameter echostr in the get request as is, where the return is neither return nor ajaxReturn, but use echo. If we develop with thinkPHP, we will directly use echo I ('echostr'). That's it. Then the interface is verified successfully.

2 the function of QR code with parameters

Wechat has two kinds of QR codes with parameters, one is temporary QR code and the other is permanent QR code, but there is a limit on the number of permanent QR codes. The function I want to achieve this time is to use the product on the website when the user is not logged in. For example, to get a detailed quotation for a product, but do not want to register, but want to save the quotation, at this time the web page can generate a QR code As long as the user scans the QR code with Wechat, official account will send an one-day picture and text message to the user. After the picture and text message is clicked, the quotation that the user has just obtained is available, and you can click to view it at any time and share it with friends for price comparison. So the temporary QR code can be used normally.

The above is how I use it, and the following describes the whole process of interaction:

When the user scans the QR code, if the user follows the official account, the user will directly go to the conversation page with the official account, and the Wechat server will push a message to the server we set in the previous step, which can carry a custom parameter. If the user does not follow the official account, the user will first jump to the official account follow page. After clicking on follow, the user will directly go to the official account session page. At this time, the Wechat server will also push an event message to the URL set by us, carrying our custom parameters. We can control the next action according to this parameter and event type.

3 specific development process

3.1 get access_token

This access_token is the credential for our program to call Wechat API. The current validity period is 7200 seconds, so we need to update access_token regularly.

How to get it:

Method: GETurl: https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

The parameters APPID and APPSECRET are the APPID and APPSECRET of our official account, which can be found in the official account-> basic configuration of Wechat. The following JSON data will be returned if the call succeeds:

{"access_token": "ACCESS_TOKEN", "expires_in": 7200}

Access_token is the calling API credential, and expire_in is the valid time of token.

I store the access_token in the database, save the expiration time at the same time, and then encapsulate the common function getWechatAccessToken (). Every time I check whether the access_token expires, and if it expires, I can get it again, otherwise I can directly use the access_token saved in the database. I forgot where to read it, and there should be a limit on the number of times this access_token can be obtained every day. Here is the implementation of getWechatAccessToken ():

1 / / get access_token 2 function getWechatAccessToken () {3$ wechatInfo = M ('wechat_info')-> select (); 4$ wechatInfo = array_reduce ($wechatInfo, create_function (' $result, $conf_name,'$result [$v ["conf_name"]] = $vbot return $result;'); 5$ expireTime = $wechatInfo ['PUBLIC_WECHAT_ACCESSTOKEN_EXPIRES'] [' conf_value'] / / never mind before, it is my database that sets 6 / 7 if (time ()) accordingly.

< $expireTime){ //access_token未过期 8 return $wechatInfo['PUBLIC_WECHAT_ACCESSTOKEN']['conf_value']; 9 }else{ //access_token过期,重新获取10 $baseUrl = C('WECHAT_PUBLIC_GET_ACCESS_TOKEN');11 $url = str_replace("##APPSECRET##", $wechatInfo['PUBLIC_WECHAT_APPSECRET']['conf_value'], str_replace("##APPID##", $wechatInfo['PUBLIC_WECHAT_APPID']['conf_value'], $baseUrl));12 $result = file_get_contents($url);13 $result = json_decode($result, true);14 15 if (array_key_exists('errorcode', $result)){ //失败重试一次16 return false;17 }else{18 M('wechat_info')->

Where (array ('conf_name' = >' PUBLIC_WECHAT_ACCESSTOKEN'))-> save (array ('conf_value' = > $result [' access_token'])); 19 M ('wechat_info')-> where (array (' conf_name' = > 'PUBLIC_WECHAT_ACCESSTOKEN_EXPIRES'))-> save (array (' conf_value' = > time () + $result ['expires_in']-200)); 20 return $result [' access_token'] 21} 22} 23} C ('WECHAT_PUBLIC_GET_ACCESS_TOKEN') = https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

After this is sealed, we can use it with peace of mind every time.

3.2 create a temporary QR code

3.2.1 get ticket

Request method: POST API: https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN POST data: {"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}

The TOKEN in the interface URL is the valid time for the expire_seconds to be the QR code in the access_token,post data obtained in 3.1.The maximum is 30 days. The temporary QR code of action_name is always QR_SCENE,scene_id, that is, our custom parameter, which is a 32-bit non-zero integer. I set it as the ID of the order in the application. When the Wechat server pushes the event, it will return this value to the API we set. Then I will display the corresponding order data on the web page according to this value, which is later.

The following is the encapsulated method of generating temporary QR codes:

/ / create temporary QR code function getTemporaryQrcode ($orderId) {$accessToken = getWechatAccessToken (); $url = str_replace ("# # TOKEN##", $accessToken, C ('WECHAT_PUBLIC_GET_TEMPORARY_TICKET')); $qrcode =' {"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id":'. $orderId.'}}'; $result = api_notice_increment ($url, $qrcode) $result = json_decode ($result, true); return urldecode ($result ['url']);}

The method api_notice_increment () is a POST method function I encapsulated. I have tried many POST methods, probably because the Wechat interface has relatively strict restrictions on POST methods and parameters, which has wasted a long time. Finally, I found an encapsulated POST method that can be used on the Internet. I suggest you try it yourself first. If Wechat returns an error, use this method. At least when I test the Wechat interface, I use postman to return errors, and I must use the JSON string, it must be a very strict JSON string. Here is the method:

Function api_notice_increment ($url, $data) {$ch = curl_init (); $header = "Accept-Charset: utf-8"; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt ($ch, CURLOPT_HTTPHEADER, $header) Curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt ($ch, CURLOPT_AUTOREFERER, 1); curl_setopt ($ch, CURLOPT_POSTFIELDS, $data); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); $tmpInfo = curl_exec ($ch); if (curl_errno ($ch)) {curl_close ($ch) Return $ch;} else {curl_close ($ch); return $tmpInfo;}}

GetTemporaryQrcode () has a parameter in the configuration file to show you, which is actually the Wechat API link:

C ('WECHAT_PUBLIC_GET_TEMPORARY_TICKET') = https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=##TOKEN##

The return value of this API is:

{"ticket": "gQH47joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2taZ2Z3TVRtNzJXV1Brb3ZhYmJJAAIEZ23sUwMEmm3sUw==", "expire_seconds": 60, "url": "http:\ /\ / weixin.qq.com\ / Q\ / kZgfwMTm72WWPkovabbI"}

Where ticket is the credential that we use to make the next call, expire_seconds is the validity period of the QR code, and url is the link opened after scanning the QR code we generated. So if we implement the method of generating the QR code by ourselves, we don't have to call it in the next step. I stop at this step, return the value of url directly, and then use the value of this url to generate the QR code locally. PHP to generate QR code can use phpqrcode, very easy to use. The next step is also briefly mentioned:

3.2.2 get the address of the QR code

Request method: GET API: https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET

The return value of this API is an image, which can be displayed or downloaded directly. We have used it, so we don't know how to display it.

3.3 what happens after the user scans the QR code

3.3.1 what happened after the scan

As mentioned above, the user scans the temporary QR code generated by us. If the user does not follow the official account, he will first jump to the follow page of the official account. After clicking the follow, the user will enter the session page of the official account. At the same time, an event will be pushed to the interface we set. If the user has already followed, the user Wechat will jump directly to the official account session page, and then the Wechat server will push an event to the interface we set.

Whether users follow it or not, the events pushed by Wechat server are similar, except that the events pushed by new users will be preceded by a prefix scene_id. The following is a description of Wechat's public platform documents:

When the user is not paying attention Event push / / developer Wechat / / sender account (openid) 123456789 / / message creation time (integer) / / message type event / / event type (subscribe) / / event key value after following Qrscene_ is prefixed, followed by the QR code parameter value / / QR code tick value, which can be used in exchange for QR code pictures.

Event push when the user has followed it

/ / developer Wechat account / / sender account (openid) 123456789 / / message creation time / / message type event / / event type event / / event key value, which is a 32-bit unsigned integer That is, the ticke of the scene_id / / QR code when creating the QR code, which can be used in exchange for the QR code picture.

3.3.2 what are we going to do

We need to receive this event in the URL interface we filled in, and then get what we need to do what we want to do. Because the function I want to implement is relatively simple, I just need to get the scene_id, because this is the order data I want to show to the user. The following is the receiving and processing part I wrote, which is relatively simple. Let's mainly take a look at how to receive Wechat push events:

Public function urlRedirect () {$postStr = $GLOBALS ["HTTP_RAW_POST_DATA"]; $postObj = simplexml_load_string ($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = (string) $postObj- > FromUserName; $EventKey = trim ((string) $postObj- > EventKey); $keyArray = explode ("_", $EventKey) If (count ($keyArray) = = 1) {/ / followers scan $this- > sendMessage ($fromUsername, $EventKey);} else {/ / unfollowed push event $this- > sendMessage ($fromUsername, $keyArray [1]);}}

I did not use other parameters, but just got the order ID I wanted according to different push events, and then it is actually equivalent to you talking to the code-scanning user with the official account customer service here. The sendMessage () called in the previous code uses the customer account to send a picture and text message to the code-scanning user, because when I get the scen_id, I also get the user's openid, which can be used to send a message to the user.

Here is the sendMessage () method:

/ / send a message to the user, click to jump to the quotation page public function sendMessage ($openid,$orderId) {$url = str_replace ('# # TOKEN##', getWechatAccessToken (), C ('WECHAT_SEND_MESSAGE')); $redirectUrl = str_replace ("# # ORDERID##", $orderId, str_replace ("# # OPENID##", $openid, C (' WECHAT_REDIRECT_URL_PRE') $orderInfo = M ('order')-> where (array (' orderid' = > $orderId)) > field (array ('totalMoney',' savedMoney', 'roomarea'))-> find (); $description = str_replace ("# # ROOMAREA##", intval ($orderInfo [' roomarea'] * 1.25), C ('WECHAT_MESSAGE_BRIEF')); $description = str_replace ("# # TOTALBUDGET##", $orderInfo [' totalMoney'], $description) $description = str_replace ("# # MARKETBUDGET##", $orderInfo ['totalMoney'] + $orderInfo [' savedMoney'], $description); $description = str_replace ("# # SAVEMONEY##", $orderInfo ['savedMoney'], $description); $dataStr =' {"touser": "'. $openid. "," msgtype ":" news "," news ": {" articles ": [{" title ":"'. C ('WECHAT_MESSAGE_TITLE'). "description": ". $description. "url": ". $redirectUrl. "picurl": ". C ('WECHAT_MESSAGE_PICURL'). '"}]}'; api_notice_increment ($url, $dataStr);}

C ('WECHAT_SEND_MESSAGE') =' https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=##TOKEN##' as for the following large piece of str_replace, which is just the text sent to the user in the group, you need to pay attention to the format of $dataStr, which requires that the JSON string is relatively strict, and all strings must be enclosed in double quotation marks. The Wechat API has strict restrictions on POST parameters.

The following is the POST data format required to send picture and text messages in the developer's document of Wechat public platform:

{"touser": "OPENID", "msgtype": "news", "news": {"articles": [{"title": "Happy Day", "description": "Is Really A Happy Day", "url": "URL", "picurl": "PIC_URL"} {"title": "Happy Day", "description": "Is Really A Happy Day", "url": "URL", "picurl": "PIC_URL"}

Url is the address opened by the user after clicking on this message. At this time, I set up an address of my own website, which is a get request address with the parameters of the user's openid and order id, so that the user can click on the picture and text message to see the content of the order he has just placed, because the user's Wechat profile picture and nickname need to be displayed on the web page, so I put openid in the parameters. Get the user's personal information and order data before the page is loaded, and then display the page. The process is as follows: the user is not logged in to place the order-> generate the Wechat QR code-> the user scans the code to follow the official account-> View the order details. And because the link after the picture and text message is opened with the parameters of the user's openid and the order ID of the order, no matter where it is shared, it can be accessed by any browser, and it also displays the user's profile picture and nickname information, which is also an effect that I want to achieve.

The above is all the contents of the article "sample Analysis of Wechat Development of QR Code with parameters". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report