


Detailed explanation of the instructions for using php WeChat to develop QR codes with parameters
Mar 16, 2017 pm 03:00 PMThis article mainly explains in detail the instructions for using php WeChat to develop QR codes with parameters. Interested friends can refer to
The recent development of WeChat PC webpage WeChat related functions. From a novice's perspective, the documents of WeChat public accounts are still difficult to understand. Most of the posts found online basically copy the documents provided on the WeChat public platform. There are still problems in the process of developing WeChat parameterized QR codes. I have encountered many pitfalls, so I will record my development process in more detail here, hoping it will be helpful to everyone.
I am using the authentication service account for this development.
1 Access
First enter the WeChat official account-> Basic configuration
The following is the basic configuration page, fill in the server address in the URL, this address It is an interface that accepts WeChat push events. I developed the program using the thinkPHP framework. In one of the Module (Decoration) Create a new class in the Action directory, for example: WechatAction.class.php, and create a new public method in the Action, for example: URLRedirect (), then what is filled in this URL is http://[IP]:[port]/index.php/Decoration/Wechat/UrlRedirect, and then fill in Token, Token Fill it in as you like, EncodingAESKey is OK or not, and then click Confirm. WeChat will send a get request to this URL, which contains many parameters, most of which allow us to check whether this visit is correct. It was requested by the WeChat server, but I have not verified it myself. His requirement is that if we verify successfully, a parameter echostr in the get request will be returned as is. The return here is not return, nor Instead of ajaxReturn, use echo. If you develop with thinkPHP, just use echo I('echostr'); directly. Then the interface verification is successful.
2 The role of QR code with parameters
There are two kinds of QR codes with parameters in WeChat, one is temporary QR code QR code, one is a permanent QR code, but there is a limit to the number of permanent QR codes generated. The function I want to implement this time is for users to use products on the website without logging in, such as obtaining a product Detailed quotation, but do not want to register, but want to save the quotation. At this time, the web page can generate a QR code. The user only needs to scan the QR code with WeChat, and the official public account will send graphic messages to the user for one day. , after clicking on the graphic message, you will see the quotation the user has just obtained, and you can click to view it at any time and share it with friends for price comparison. Therefore, the temporary QR code can be used normally.
The above is how I use it. Here is an introduction to the entire interaction process:
3 Specific development process
3.1 Obtain access_token
This access_token is the certificate for our program to call the WeChat interface. The current validity period is 7200 seconds, so we need to update it regularly access_token.
Getting 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 official account, which can be found in the WeChat official account-> Basic configuration, and the call is successful The following JSON data will be returned:
{"access_token":"ACCESS_TOKEN","expires_in":7200}
where access_token is the calling interface For credentials, expire_in is the token validity time.
I personally store the access_token in the database, save the expiration time, and then encapsulate the public function getWechatAccessToken(). Each time, first check whether the access_token has expired. If it expires, re-obtain it. Otherwise, use the database to save it directly. The access_token is sufficient. I forgot where I saw it. There should be a limit to the number of times this access_token can be obtained per day. The following is the specific implementation of getWechatAccessToken():
//獲取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']; //前面不用管,是我數(shù)據(jù)庫相應(yīng)設(shè)置 if (time() < $expireTime){ //access_token未過期 return $wechatInfo['PUBLIC_WECHAT_ACCESSTOKEN']['conf_value']; }else{ //access_token過期,重新獲取 $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; }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
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 we obtained in 3.1, expire_seconds in the post data is The QR code is valid for up to 30 days. If the action_name is a temporary QR code, it is fixed to QR_SCENE. The scene_id is our custom parameter. It is a 32-bit non-0integer. I set it in the application. The ID of the order. When the WeChat server pushes the event, it will return this value to the interface we set. Then I will use this value to get the corresponding order data and display it on the web page. This is a story later.
The following is the encapsulated method of generating temporary QR codes:
//創(chuàng)建臨時二維碼 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 encapsulated by me A POST method function. I have tried many POST methods. Maybe because the WeChat interface has strict restrictions on POST methods and parameters, this wasted a long time. Finally, I found an encapsulated POST method that can be used online. I recommend it to everyone. Try it yourself first. If WeChat returns an error, use this one. At least when I tested the WeChat interface, I used postman to test and all returned errors, and JSONString must be used. It must be very Strict JSON string. The following is this 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() There is a parameter in Configuration File for everyone to see, it is actually WeChat 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":60,"url":"http:\/\ /weixin.qq.com\/ q\/kZgfwMTm72WWPkovabbI"}
where ticket is the voucher we use to make the next call, expire_seconds is the validity period of the QR code, and url is the link we opened after scanning the QR code we generated. . So if we implement the method of generating QR code ourselves, we don’t need to make the next call. I stop at this step and directly return the value of the url, and then use the value of this url to generate the QR code and store it locally. Can. You can use phpqrcode to generate QR codes in PHP, which is very easy to use. Let’s briefly mention the next step:
3.2.2 獲取二維碼地址
請求方式: GET
接口:https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
這個接口的返回值是一張圖片,可以直接展示或者下載,我們有具體使用過,所以也不知道應(yīng)該怎么展示。
3.3 用戶掃描二維碼之后發(fā)生的事情
3.3.1 掃描后發(fā)生了什么
上面提到了,用戶掃描我們生成的臨時二維碼,如果用戶未關(guān)注公眾號,則首先會跳轉(zhuǎn)到公眾號的關(guān)注頁面,點擊關(guān)注后,會進入公眾號的會話頁面,同時會給我們設(shè)置的接口推送一個事件。如果用戶已經(jīng)關(guān)注了,用戶微信會直接跳轉(zhuǎn)到公眾號會話頁面,然后微信服務(wù)器會給我們設(shè)置的接口推送一個事件。
用戶關(guān)注與否微信服務(wù)器給我們推送的事件是差不多的,只是新關(guān)注用戶推送的事件中scene_id前面會加一個前綴。下面是微信公眾平臺文檔的說明:
用戶未關(guān)注時,進行關(guān)注后的事件推送
<xml><ToUserName><![CDATA[toUser]]></ToUserName> //開發(fā)者微信號 <FromUserName><![CDATA[FromUser]]></FromUserName> //發(fā)送者賬號(openid) <CreateTime>123456789</CreateTime> //消息創(chuàng)建時間(整型) <MsgType><![CDATA[event]]></MsgType> //消息類型 event <Event><![CDATA[subscribe]]></Event> //事件類型(subscribe) <EventKey><![CDATA[qrscene_123123]]></EventKey> //事件KEY值,qrscene_為前綴,后面為二維碼參數(shù)值 <Ticket><![CDATA[TICKET]]></Ticket> //二維碼ticke值,可以用來換取二維碼圖片 </xml>
用戶已關(guān)注時的事件推送
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> //開發(fā)者微信號 <FromUserName><![CDATA[FromUser]]></FromUserName> //發(fā)送者賬號(openid) <CreateTime>123456789</CreateTime> //消息創(chuàng)建時間 <MsgType><![CDATA[event]]></MsgType> //消息類型event <Event><![CDATA[SCAN]]></Event> //事件類型 event <EventKey><![CDATA[SCENE_VALUE]]></EventKey> //事件key值,是一個32位無符號整數(shù),即創(chuàng)建二維碼時的二維碼scene_id <Ticket><![CDATA[TICKET]]></Ticket> //二維碼的ticke,可以用來換取二維碼圖片 </xml>
3.3.2 我們要做些什么
我們需要在自己填寫的URL接口中接收這個事件,然后拿到我們需要的東西做我們想干的事兒。因為我要實現(xiàn)的功能比較簡單,只需要拿到scene_id即可,因為這是我要展示給用戶看的訂單數(shù)據(jù)。下面是我寫的接收和處理部分,比較簡單,主要看一下應(yīng)該怎么接收微信推送的事件:
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){ //已關(guān)注者掃描 $this->sendMessage($fromUsername, $EventKey); }else{ //未關(guān)注者關(guān)注后推送事件 $this->sendMessage($fromUsername, $keyArray[1]); } }
我沒有使用其他參數(shù),只是根據(jù)不同的推送事件拿到我想要的訂單ID,然后這時候其實相當于你在這里用公眾號的客服在跟掃碼的這個用戶對話,上段代碼中調(diào)用的sendMessage()是使用客戶賬號給掃碼用戶發(fā)送一個圖文消息,因為我在拿scen_id的同時也拿到了用戶的openid,可以利用這個給用戶發(fā)送消息。
下面是sendMessage()方法:
//給用戶發(fā)送圖文消息,點擊跳轉(zhuǎn)到報價頁面 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##' 至于下面的一大段str_replace,就是在組給用戶發(fā)送的文字而已,需要注意$dataStr的格式,這里面要求JSON字符串比較嚴格,必須所有的字符串都用雙引號括起來。微信接口對POST參數(shù)的限制真心嚴格。
下面是微信公眾平臺開發(fā)者文檔中要求發(fā)送圖文消息的POST data格式:
{ "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是用戶點擊這個消息之后打開的地址,這個時候我就組了一個自己網(wǎng)站的地址,是一個get請求地址,里面攜帶參數(shù)是用戶的openid和訂單id,這樣用戶點擊開圖文消息就可以看到自己剛才下單的內(nèi)容了,因為需要在網(wǎng)頁上展示用戶的微信頭像和昵稱,所以我把openid也放到參數(shù)里,在頁面加載前先拿到用戶的個人信息和訂單數(shù)據(jù),再展示網(wǎng)頁。這樣流程:用戶未登錄下單 -> 生成微信二維碼 -> 用戶掃碼關(guān)注公眾號 -> 查看訂單詳細信息 就完成了。而且因為這個圖文消息打開后的鏈接攜帶的參數(shù)是這個用戶的額openid和其下單的訂單ID,不管分享到哪兒,用什么瀏覽器打開都是可以訪問的,且展示的也是這個用戶的頭像和昵稱信息,這也是我要實現(xiàn)的一個效果。
The above is the detailed content of Detailed explanation of the instructions for using php WeChat to develop QR codes with parameters. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)