Application of QR code with parameter based on PHP for micro-credit development

Source: Internet
Author: User
Tags cdata openid ticket
This article is mainly for you to introduce the PHP development with the parameters of the use of two-dimensional code, interested in small partners can refer to

Recently do PC-side Web page related function development, from a novice's point of view, the public number of the document is not well understood, the online search for most of the posts are basically the copy of the public platform to the document, the development of two-dimensional code with parameters in the process or encountered a lot of pits, in this process of my development more detailed records, We hope to help you.

I am using the certification service number for this development.

1 access
First access to the public number--basic configuration
Here is the basic configuration of the page, fill in the URL of the server address, which is an interface to accept the push event, I am using the thinkphp framework developed by the program, in one of the module (decoration) of the action directory to create a new class, such as called: WechatAction.class.php, create a new public method in the action, such as the name: Urlredirect (), then fill in this URL is http://[ip]:[port]/index.php/ Decoration/wechat/urlredirect , and then fill in Token,token to fill, encodingaeskey to do, and then click Confirm, will send a GET request to this URL, which contains a lot of parameters, Most of them are let ourselves check whether this visit is not a server request, I did not verify that his request is if we check the success, that is, return the GET request is a parameter echostr, here is not return, nor ajaxreturn, and use Echo, If developed with thinkphp, use echo I (' echostr ') directly; Can. The interface is then validated successfully.

2 function of two-dimensional code with parameters
With parameter two-dimensional code, one is a temporary QR code, a permanent two-dimensional code, but the generation of permanent two-dimensional code is limited, I want to achieve the function of the user is not logged in the case of the use of products on the site, such as to obtain a detailed price of a product, but do not want to register, but want to save this This time the page can generate a two-dimensional code, users as long as a sweep of the QR code, the official public will send the user a day text message, the text message point is the user just get a quote, and can click to view and share to friends for comparison. So the temporary QR code can be used normally.
The above is how I use, the following describes the whole process of Interaction:

When the user scans the QR code, if the user is concerned about the public number, the user will go directly to the public number of the session page, the server will give us the server URL set in the previous step to push a message, which can carry a custom parameter. If the user does not pay attention to the public number, then the user will first jump to the public attention page, the user click on the attention, will go directly to the public number of the session page, the server will also give us the URL set to push an event message, carry our custom parameters, we can according to this parameter and event type to control the next action.

3 Specific development process

3.1 Get Access_token
This access_token is our program call interface credentials, the current validity is 7,200 seconds, so we need to update access_token regularly.
How to obtain:
Method: GET
URL: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 public number, which can be found in the basic configuration of the public number, which will return the following JSON data:
{"Access_token": "Access_token", "expires_in": 7200}

Where Access_token is called the interface credentials, expire_in is the token valid time.
I am the Access_token exists in the database, while saving the expiration time, and then encapsulating the common function getwechataccesstoken (), each time first check whether the Access_token is expired, if the expiration is re-acquired, Otherwise directly using the database saved Access_token can, I forgot where to see Add, this access_token the number of times per day should be limited. The following is a concrete implementation of Getwechataccesstoken ():

Get 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 ']; No, no, it's me. Database Settings if (Time () < $expireTime) {//access_token not expired return $wechatInfo [' Public_wechat_accesstoken '] [' Co Nf_value '];  }else{//access_token expired, re-acquired $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)) {//Failed retry once return false; }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

Once we've packaged this, we can use it at ease every time.

.2 Creating a temporary QR code

3.2.1 Get Ticket3

Request Method: POST
Interface: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}}}
Token in the interface URL is the Access_token,post data we obtained in 3.1 expire_seconds is the effective time of the QR code, up to 30 days, action_name temporary QR code fixed is Qr_scene,scene _id that is our custom parameter, is a 32-bit non-0 integer, I set it in the application as the ID of the order, the server pushes the event will return this value to the interface we set, and then I will be based on this value to get the corresponding order data displayed on the page, this is something.

Here is the encapsulated method for generating the temporary QR code:

Creates 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 I encapsulated, I tried a lot of post methods, perhaps due to the interface to the Post method and parameters of strict restrictions, this wasted a long time, Finally found on the Internet A can be used in a packaged post method, it is recommended that you first try, if you return an error, use this bar, at least I test this interface with Postman Test return is an error, and must use JSON string, must be very strict JSON string. Here's how to do this:

function Api_notice_increment ($url, $data) {$ch = Curl_init (); $header = "Accept-charset:utf-8"; curl_setopt ($ch, Curlop T_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 everyone to see, in fact, is the interface link:
C (' wechat_public_get_temporary_ticket ') = https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=# #TOKEN # #

The return value of this interface is:
{"Ticket": "gqh47joaaaaaaaaaasxodhrwoi8vd2vpeglulnfxlmnvbs9xl2taz2z3tvrtnzjxv1brb3zhymjjaaiez23suwmemm3suw==", " Expire_seconds ":", "url": "Http:\/\/weixin.qq.com\/q\/kzgfwmtm72wwpkovabbi"}

Where ticket is the credential that lets us make the next call, Expire_seconds is the validity period of the QR code, and the URL is the link to open after the QR code we generated. So if we implement the method of generating two-dimensional code, we do not need to make the next call, I myself in this step stop, directly return the value of the URL, and then use the value of this URL to generate two-dimensional code exists locally. PHP generates two-dimensional code can use Phpqrcode, very useful. The next step is also broadly mentioned:

3.2.2 Get two-dimensional code address
Request Method: GET
Interface:Https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
The return value of this interface is a picture, can be directly displayed or downloaded, we have specific use, so do not know how to show.

3.3 What happens after the user scans the QR code
What happened after the 3.3.1 scan?
As mentioned above, the user scans our generated temporary QR code, if the user does not pay attention to the public number, the first will jump to the public attention page, click on the attention, will enter the public number of the session page, and will give us the interface set to push an event. If the user is already concerned, the user jumps directly to the public number session page, and the server pushes an event to the interface we set up.

User concerns or not the event that the server gives us pushes is similar, but the new attention to the user pushes the event in front of the scene_id will add a prefix. The following is a description of the public platform documentation:

Event pushes after attention when the user is not concerned

<xml><tousername><! [cdata[touser]]></tousername>//Developer number <fromusername><!                [cdata[fromuser]]></fromusername>//Sender account (OpenID) <CreateTime>123456789</CreateTime> Message creation time (integer type) <msgtype><! [cdata[event]]></msgtype>//Message type event<event><! [cdata[subscribe]]></event>//Event Type (subscribe) <eventkey><! [cdata[qrscene_123123]]></eventkey>//Event key value, Qrscene_ as prefix, followed by the QR code parameter value <ticket><! [cdata[ticket]]></ticket>//Two D code Ticke value, can be used in exchange for two-dimensional code picture </xml>

Event push when the user is already concerned

<xml><tousername><! [cdata[touser]]></tousername>//Developer number <fromusername><! [cdata[fromuser]]></fromusername>//Sender account (OpenID) <CreateTime>123456789</CreateTime>/ /Message creation Time <msgtype><! [cdata[event]]></msgtype>     //message type event<event><![ Cdata[scan]]></event>//Event Type event<eventkey><! [cdata[scene_value]]></eventkey>   //Event key value, is a 32-bit unsigned integer, which is the QR code when creating the QR code scene_id<ticket><![ Cdata[ticket]]></ticket>      //Two-D code Ticke, can be used to exchange QR code images </xml>

3.3.2, what are we going to do?

We need to receive this event in the URL interface we fill out, and then get what we need to do what we want to do. Because I want to implement the function is relatively simple, just need to get scene_id, because this is I want to show the user to see the order data. Here is my write the Receiving and Processing section, relatively simple, mainly to see how to receive the Push event:

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{//Not concerned about post-push events   $this->sendmessage ($fromUsername, $keyArray [1]);}  }

I do not use other parameters, just according to different push events to get the order ID I want, and then this is actually the equivalent of you here with the public number of customer service in the code of this user dialogue, the SendMessage () called in the previous section of the call is to use the customer account to scan the user to send a text message, Because I was taking scen_id and also got the user's OpenID, can use this to send messages to the user.

Here is the SendMessage () method:

Send a message to the user, click to jump to the Quote 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); }

where C (' wechat_send_message ') = ' https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=# #TOKEN # # ' As for the following a large section of Str_replace, is in the group to send the user text only, need to pay attention to the format of $DATASTR, where the JSON string is required to be strict, all strings must be enclosed in double quotation marks. The interface has strict restrictions on post parameters.

The following is the post data format required to send a text message 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 "   }   ]}}

Where the URL is the user click on the message opened after the address, this time I set up a site of their own address, is a GET request address, which is the user's OpenID and the order ID, so that the user click on the text message can see the content of their orders just now, Because I need to display the user's avatar and nickname on the Web page, I put OpenID in the parameters, get the user's personal information and order data before the page is loaded, and then display the webpage. This process: The user is not logged in the next order, generate two-dimensional code--user scan code attention to the public number---View the order details are complete. And because this text message opens after the link carries the parameter is the user's amount of OpenID and its order ID, no matter where to share, with what browser Open is accessible, and the display is the user's avatar and nickname information, which is what I want to achieve an effect.

Summary: The above is the entire content of this article, I hope to be able to help you learn.

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.