Recently doing micro-letter PC-side web page micro-letter related function development, from a novice's point of view, the micro-credit document is still not easy to understand, the Internet to find posts are basically copied micro-trust on the public platform to the document, the development of the micro-letter with the parameters of two-dimensional code in the process or encountered a lot of pits, This is my development process in a more detailed record, I hope to help you.
I use the authentication service number for this development.
1 access
first into the micro--> public number basic configuration
Here is the basic configuration of the page, fill in the URL of the server address, this address is to accept the micro-mail push event of an interface, I was developed using the thinkphp framework of the program, in one of the module (decoration) in the action directory to create a new class, such as: WechatAction.class.php, create a new public method in this action, such as: Urlredirect (), then fill in the URL http://[ip]:[port]/index.php/ Decoration/wechat/urlredirect , and then fill in Token,token to fill in, Encodingaeskey to do, and then click OK, micro-letter will send a GET request to this URL, which contains a lot of parameters, Most of them are let us check this visit is not a micro-trust server request, I did not verify, his request is that if we check the success, that is, return to the GET request is a parameter echostr, here is not return, not Ajaxreturn, Using ECHO, if developed using thinkphp, use echo I (' echostr ') directly; Can. Then the interface is validated successfully.
2 The function of two dimensional code with parameter
There are two types of micro-letters with parametric two-dimensional codes, one is a temporary two-dimensional code, one is 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, However, you want to save this quote, this time the page can generate a two-dimensional code, as long as the user with micro-letter sweep This two-dimensional code, the official public number will send a day message to the user, the text message is opened after the user has just received a quote, and can click to view and share to friends for comparison. So the temporary two-dimensional code can be used normally.
The above is how I use, the following describes the entire interaction process :
When the user scans this two-dimensional code, if the user is concerned about the public number, the user will go directly to the session page with the public number, the micro-trust server will give us in the previous step set up the server URL to push a message, which can carry a custom parameter. If the user is not concerned with the public number, the user will first jump to the public number attention page, users click on the attention, will go directly to the public number of the session page, the micro-trust server will also give us the URL to set up to push an event message, carry our custom parameters, we can according to this parameter and event types to do control the next move.
3 Specific development process
3.1 Get Access_token
This access_token is a voucher for our program to invoke the micro-communication interface, which is currently valid for 7,200 seconds, so we need to update access_token regularly.
Get the method:
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 micro-public number->, and the success of the call returns the following JSON data:
{"Access_token": "Access_token", "expires_in": 7200}
Where Access_token is called interface voucher, expire_in is token effective time.
I'm the one who put Access_token in the database, save the expiration time, and then encapsulate the common function getwechataccesstoken (), check access_token for expiration each time, and retrieve it if it expires. Otherwise directly using the database to save the Access_token, I forget where to see added, this access_token the number of times per day should be limited. The following is a specific implementation of Getwechataccesstoken ():
Gets the Access_token function 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 ']; Not in front of me. The database sets the IF (Time () < $expireTime) {//access_token not expired return $wechatInfo [' Public_wechat_accesstoken '] ['
Conf_value '];
}else{//access_token expired, re-acquire $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 return false; }else{M (' Wechat_info ')->where (Array (' Conf_name ' => ' Public_wechat_accesstoken '))->save (' 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 at ease every time.
.2 Creating a temporary two-dimensional 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}}}
The token in the interface URL, that is, the access_token,post data that we get in 3.1, Expire_seconds is the effective time for the two-dimensional code, up to 30 days, action_name temporary two-dimensional code is fixed is Qr_scene,scene _ID, which is our custom parameter, is a 32-bit non-0 integer, I put it in the application of the order ID, the micro-server push event will return this value to our set of interface, and then I will be based on this value to get the corresponding order data displayed on the Web page, this is something.
The following is the encapsulated method of generating a temporary two-dimensional code:
Creates a temporary two-dimensional 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, and I tried many post methods, and it was a waste of a long time since the micro-letter interface was more restrictive to post methods and parameters. Finally found on the internet can be used to encapsulate a good post method, we recommend that you try first, if the micro-letter return error, use this bar, at least I test micro-trust this interface with the postman test returned are errors, and must use the JSON string, Be sure to be very strict with JSON strings. 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 for everyone to look at, is actually a micro-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 voucher that we use to make the next call, the Expire_seconds is the validity of the two-dimensional code, and the URL is the link that is opened after the two-dimensional code scan we generated. So if we implement the method of generating two-dimensional code by ourselves, we do not need to make the next call, I will stop at this step, directly return the value of the URL, and then use the value of this URL to generate a two-dimensional code exists locally. PHP generated two-dimensional code can use Phpqrcode, very useful. The next step is to roughly mention:
3.2.2 Get the two-dimensional code address
Request Mode: 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 also do not know how to show.
3.3 What happens after a user scans a two-dimensional code
What happened after the 3.3.1 scan?
mentioned above, the user scans our generated temporary two-dimensional code, if the user does not pay attention to the public number, the first will jump to the public number of attention page, click Attention, will enter the public number of the session page, and will give us set the interface to push an event. If the user is already concerned, the user micro-letter will jump directly to the public number session page, and then the micro-trust server will give us the interface set up to push an event.
User concern or not the micro-trust server to give us the push of the event is similar, but the new focus on user-pushed events in front of scene_id will prefix. Below is a description of the micro-credit public platform documentation:
When the user is not concerned, the event pushed after the attention
<xml><tousername><! [cdata[touser]]></tousername>//Developer micro-signal
<fromusername><![ Cdata[fromuser]]></fromusername>//Sender account (OpenID)
<CreateTime>123456789</CreateTime> Message creation time (integer)
<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 two-dimensional code parameter value
<ticket><![ Cdata[ticket]]></ticket>//Two D code Ticke value, can be used in exchange for two-dimensional code picture
Event push when the user is already concerned
<xml>
<tousername><![ Cdata[touser]]></tousername>//Developer micro-signal
<fromusername><![ Cdata[fromuser]]></fromusername>//Sender account (OpenID)
<CreateTime>123456789</CreateTime> Message creation time
<msgtype><![ Cdata[event]]></msgtype> //Message type event
<event><![ Cdata[scan]]></event>//Events type event
<eventkey><![ Cdata[scene_value]]></eventkey> //Event key value, is a 32-bit unsigned integer, that is, two-dimensional code when creating a two-dimensional code scene_id
<ticket><![ Cdata[ticket]]></ticket> //Two D Ticke, can be used in exchange for two-dimensional code picture
</xml>
3.3.2, what are we going to do?
We need to receive this event in our own URL interface, and then get what we need to do what we want to do. Because I want to implement the function is relatively simple, only need to get scene_id can, because this is I want to show the user to see the order data. Here is the reception and Processing section I write, relatively simple, mainly to see how to receive the micro-mail 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) { //
->sendmessage scanned $this ($fromUsername, $EventKey);
else{//No concerns after push event
$this->sendmessage ($fromUsername, $keyArray [1]);
}
I don't use other parameters, just according to the different push events to get the order ID I want, and then in fact, it is equivalent to you here with the public number of customer service in the sweep code of this user dialogue, the previous code called SendMessage () is to use the customer account to scan code users send a message, Because I took scen_id and also got the user's OpenID, you can use this to send a message to the user.
The following 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 # #, GETWECHATACCESST
Oken (), 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 large section of Str_replace, that is, in the group to send the user text, you need to pay attention to the format of the $DATASTR, where the JSON string is more stringent, you must have all the strings are enclosed in double quotes. The limitations of the micro-letter interface for post parameters are strictly true.
The following is the post data format required to send a message in the micro-credit 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 ":" Are really A Happy day ",
" url ":" url ",
" Picurl ":" Pic_url "
}
]
}
}
The URL is the user clicks on this message opened after the address, this time I set a site on their own address, is a GET request address, which carries parameters is the user's OpenID and order ID, so that users click to open the message can see their own just the contents of the list, Because the need to display the user's micro-letter avatar and nickname, so I put OpenID also into the parameters, in the page before loading to get the user's personal information and order data, and then show the Web page. This process: The user is not logged in a single-> generated micro-letter two-dimensional code-> user Scan code attention to the public number-> view order details are complete. And because this message is opened the link carries the parameter is the user's amount of OpenID and the order ID of its orders, regardless of where to share, with what browser Open is accessible, and the display is also the user's avatar and nickname information, which is what I want to achieve an effect.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.