Php WeChat development with parameter QR code _ php instance

Source: Internet
Author: User
This article describes how to use the parameter QR code in php Development. if you are interested, refer to the development of PC-side web page functions, from the perspective of a newbie, the document of the public account is still hard to understand. most of the posts posted on the Internet are also basically copies of the documents provided by the public platform, there are still many pitfalls in the process of developing the parameter QR code. here I will record the detailed development process and hope to help you.

I am using the certification service number for this development.

1 Access
First go to the public account-> basic configuration
The following is the basic configuration page. fill in the server address in the URL. This address is an interface for accepting push events. I am a program developed using the thinkPHP framework, in which a Module (Decoration) to create a class, such as WechatAction. class. php: create a public method in the Action, for example, URLRedirect ().Http: // [IP]: [port]/index. php/Decoration/Wechat/UrlRedirectAnd then fill in the Token, Token is left blank, EncodingAESKey is OK, and then click OK, will send a get request to this URL, contains many parameters, most of these requests allow us to check whether the access is a server request. I did not verify it. his request is that, if we verify the access, an echostr parameter in the get request is returned as is, here, the return is neither return nor ajaxReturn, but echo. if thinkPHP is used for development, echo I ('echostr') is used directly. Then the interface is verified successfully.

2. functions of the two-dimensional code with parameters
There are two types of parameter QR codes, one is temporary QR codes and the other is permanent QR codes. However, the number of permanent QR codes is limited, the function I want to implement this time is to use the product on the website without logging on to the user. for example, I want to get a detailed quotation for a product but do not want to register it. However, I want to save this quotation, at this time, the webpage can generate a QR code. users only need to scan the QR code and the official public number will send a text message to the user for one day, after opening a text message, you can click to view the quotation you just obtained and share it with your friends for price comparison. So the temporary QR code can be used normally.
The above is how I use it. The following describes the entire interaction.Process:

When the user scans the QR code, if the user pays attention to the public number, the user will directly go to the session page with the public number, the server will push a message to the server URL we set in the previous step, it can carry a custom parameter. If the user does not pay attention to the public account, the user will first jump to the public account follow page. after clicking follow, the user will directly go to the public account session page, at this time, the server will push an event message to the URL we set, carrying our custom parameters. we can control the next action based on this parameter and event type.

3. specific development process

3.1 get access_token
This access_token is the credential for the interface called by our program. The validity period is 7200 seconds. Therefore, we need to update access_token regularly.
Method:
Method:GET
Url: https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = APPID & secret = APPSECRET
The APPID and APPSECRET parameters are the APPID and APPSECRET of our public account, which can be found in the Public Account-> basic configuration. if the call is successful, the following JSON data is returned:
{& Quot; access_token & quot;: & quot; ACCESS_TOKEN & quot;, & quot; expires_in & quot;: 7200}

Access_token indicates the interface call credential, and expire_in indicates the token validity period.
I have stored access_token in the database and saved the Expiration Time, and then encapsulated the public function getwechataccesen en (). each time I first check whether access_token has expired, and if it has expired, I will get it again, otherwise, you can directly use the access_token saved in the database. I forgot where to add it. the number of access_token requests per day should be limited. The specific implementation of getWechatAccessToken () is as follows:

// Obtain access_tokenfunction getWechatAccessToken () {$ wechatInfo = M ('WeChat _ info')-> select (); $ wechatInfo = array_reduce ($ wechatInfo, create_function ('$ result, $ V', '$ result [$ v ["conf_name"] = $ v; return $ result ;')); $ expireTime = $ wechatInfo ['public _ WECHAT_ACCESSTOKEN_EXPIRES '] ['conf _ value']; // skip this step. if (time () <$ expireTime) {// access_token has not expired. return $ wechatInfo ['public _ WECHAT_ACCESSTOKEN '] ['conf _ value'];} else {// access_token has expired, obtain $ baseUrl = C ('WeChat _ public_get_access_token'); $ url = str_replace ("## APPSECRET ##", $ wechatInfo ['public _ WECHAT_APPSECRET '] ['conf _ value'], str_replace ("## APPID ##", $ wechatInfo ['public _ WECHAT_APPID '] ['conf _ value'], $ baseUrl); $ result = file_get_contents ($ url); $ result = json_decode ($ result, true); if (array_key_exists ('errorcode', $ result) {// return false if a retry fails;} else {M ('WeChat _ info ') -> where (array ('conf _ name' => 'public _ WECHAT_ACCESSTOKEN ')) -> save (array ('conf _ value' => $ result ['Access _ token']); M ('WeChat _ info ') -> where (array ('conf _ name' => 'public _ WECHAT_ACCESSTOKEN_EXPIRES ')-> save (array ('conf _ value' => time () + $ result ['expires _ in']-200); return $ result ['Access _ token'] ;}}

C ('WeChat _ PUBLIC_GET_ACCESS_TOKEN ') = https://api.weixin.qq.com/cgi-bin/token? Grant_type = client_credential & appid = APPID & secret = APPSECRET

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

. 2. create a temporary QR code

3.2.1 get ticket3

Request method: POST
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 access_token we obtained in 3.1. in The post data, expire_seconds is the validity period of the QR code, which is 30 days at most. if the temporary QR code of action_name is fixed, it is QR_SCENE, scene_id is our custom parameter. it is a 32-bit non-0 integer. I set it as the order ID in the application, when the server pushes an event, it will return this value to the interface we set, and then I will display the corresponding order data on the webpage based on this value.

The following describes how to generate a temporary QR code:

// Create a 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 encapsulated by me. I have tried many POST methods, probably because the interface has strict restrictions on POST methods and parameters, this took a long time, and finally found a encapsulated POST method on the internet. we suggest you try it yourself first. If an error is returned, use this method, at least errors are returned when I test this interface using postman. JSON strings must be used and very strict JSON strings must be used. The method is as follows:

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 for you to see. it is actually an interface link:
C ('WeChat _ PUBLIC_GET_TEMPORARY_TICKET ') = https://api.weixin.qq.com/cgi-bin/qrcode/create? Access_token ### TOKEN ##

The returned value of this interface is:
{"Ticket": "expiration =", "expire_seconds": 60, "url": "http: \/weixin.qq.com \/q \/kZgfwMTm72WWPkovabbI "}

Here, ticket is the credential used for the next call. expire_seconds is the validity period of the QR code, and url is the link opened after the QR code is scanned. Therefore, if we implement the QR code generation method, we do not need to perform the next call. I stopped at this step and directly returned the url value, then, use the url value to generate a QR code that exists locally. PHP can use phpqrcode to generate a QR code, which is quite useful. The next step is also roughly described as follows:

3.2.2 obtain the QR code address
Request method: GET
Https://mp.weixin.qq.com/cgi-bin/showqrcode? Ticket = TICKET
The returned value of this interface is an image, which can be directly displayed or downloaded. we have used it, so we do not know how to display it.

3.3 What happened after the user scanned the QR code
3.3.1 What happened after scanning
As mentioned above, the user scans the temporary QR code we generate. if the user does not pay attention to the public number, the user will first jump to the public number follow page, click follow, the session page of the public account is displayed, and an event is pushed to the interface we set. If the user has already noticed the event, the user will jump directly to the public account session page, and the server will push an event to the interface we set.

Whether the user pays attention to the events pushed by the server to us is similar, but a prefix is added before scene_id in the events pushed by the new user. The following is a description of the public platform documentation:

If you do not pay attention to it, push the following events

 
  toUser
  // Developer id
  FromUser
  // Sender account (openid)
  
   
123456789
  // Message creation time (integer)
  event
  // Message type event
  subscribe
  // Subscribe)
  qrscene_123123
  // Event KEY value. qrscene _ is the prefix, followed by the QR code parameter value.
  TICKET
  // QR code ticke value, which can be used in exchange for QR code images
  

Event push when the user is concerned

 
  toUser
  // Developer id
  FromUser
  // Sender account (openid)
  
   
123456789
  // Message creation time
  event
  // Message type event
  SCAN
  // Event type
  SCENE_VALUE
  // Event key value, which is a 32-bit unsigned integer, that is, the two-dimensional code scene_id
  TICKET
  // The ticke of the QR code, which can be used in exchange for the QR code image
 

3.3.2 What should we do

We need to receive this event in our own URL interface, and then get what we need to do what we want. Because the functions I want to implement are relatively simple, I only need to get scene_id, because this is the order data I want to display to users. The following section describes how to receive and process 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) {// scanned by someone else $ this-> sendMessage ($ fromUsername, $ EventKey );} else {// Push event $ this-> sendMessage ($ fromUsername, $ keyArray [1]) after followers;}

I didn't use other parameters. I just got the order id I want based on different push events, in this case, the customer service that uses the public account is talking to the user who scanned the code. the sendMessage () called in the previous code () the customer account is used to send a text message to the QR code user, because I also get the user's openid while getting scen_id, which can be used to send messages to the user.

The sendMessage () method is as follows:

// Send a text message to the user. click to jump to the 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 segment of str_replace, it is the text sent to the user in the group. Note that the format of $ dataStr requires strict JSON strings, all strings must be enclosed in double quotation marks. The interface imposes strict POST parameter restrictions.

The following is the POST data format required to send text and text messages in the public platform developer documentation:

{ "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"   }   ] }}

Here, the url is the address opened after the user clicks the message. at this time, I have a website address, which is a get request address, the parameters include the user's openid and order id, so that you can click the text message to view the content you just placed, because you need to display the user's profile picture and nickname on the web page, so I put the openid in the parameter. before loading the page, I first get the user's personal information and order data, and then display the webpage. The process is as follows: the user has not logged on to order-> generate a QR code-> Scan the QR code to follow the public number-> view the order details. In addition, the link after the text message is opened contains the user's openid and the order ID. no matter where the message is shared, it can be accessed in any browser, the user's profile picture and nickname information are displayed, which is also an effect I want to achieve.

The above is all the content of this article. I hope it will be helpful to everyone's learning, and I hope you can support your own home.

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.