Home > Article > Backend Development > Use of QR code with parameters in php WeChat development_php example
Recently I have been developing WeChat-related functions for the WeChat PC web page. From a novice’s perspective, the documents of WeChat public accounts are still difficult to understand. Most of the posts found online are basically copies of the documents provided on the WeChat public platform. , I still encountered many pitfalls in the process of developing WeChat QR code with parameters. I will record my development process in more detail here, hoping it will be helpful to everyone.
I am using a certification 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 is an interface for accepting WeChat push events. I developed the program using the thinkPHP framework. Create a new class in the Action directory of one of the Modules (Decoration), such as Call: WechatAction.class.php, create a new public method in the Action, for example: URLRedirect(), then fill in the URL is http://[IP]:[port]/index.php/ Decoration/Wechat/UrlRedirect, then fill in the Token, fill in the Token as you like, EncodingAESKey or not, then click Confirm, WeChat will send a get request to this URL, which contains many parameters, most of which are for us to Check whether this visit was requested by the WeChat server. I have not verified it myself. His request is that if we check successfully, that is, echostr, a parameter in the get request, will be returned as is. The return here is not return or ajaxReturn, but use echo. If you develop with thinkPHP, just use echo I('echostr'); directly. Then the interface verification is successful.
2 The function of QR code with parameters
There are two kinds of QR codes with parameters in WeChat, one is temporary QR code and the other is permanent QR code. However, there is a limit on the number of permanent QR codes generated. The function I want to implement this time When the user uses a product on the website without logging in, for example, to obtain a detailed quotation for a certain product but does not want to register, but wants to save the quotation, the web page can generate a QR code at this time, and the user only needs to scan it using WeChat With this QR code, the official public account will send a graphic message to the user for one day. After clicking on the graphic message, it will be the quotation the user has just obtained, and they 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 interactive process:
3 Specific development process
3.1 Get 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 the 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 official account. They can be found in the WeChat official account -> Basic configuration. If the call is successful, the following JSON data will be returned:
{"access_token":"ACCESS_TOKEN","expires_in":7200}
I personally store the access_token in the database, save the expiration time, and then encapsulate the public function getWechatAccessToken(). Each time, I first check whether the access_token has expired. If it expires, obtain it again. Otherwise, I can directly use the access_token saved in the database. I forgot to I read somewhere that 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']; //前面不用管,是我数据库相应设置 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
封装好这个之后,我们每次就可以安心的使用了。
.2 创建临时二维码
3.2.1 获取ticket3
请求方式: POST
接口:https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN
POST数据: {"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}
接口URL中的TOKEN即我们在3.1中获取的access_token,post数据中expire_seconds是二维码的有效时间,最多为30天,action_name临时二维码的话固定就是QR_SCENE,scene_id即我们自定义参数,是个32位非0整数,我在应用中把它设为订单的ID,微信服务器推送事件的时候会把这个值返回给我们设置的接口中,然后我会根据这个值去拿相应的订单数据展示在网页上,这是后话。
下面是封装的生成临时二维码的方法:
//创建临时二维码 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']); }
其中的方法 api_notice_increment() 是我封装的一个POST方法函数,我试过很多POST的方法,可能由于微信接口对POST方法和参数的限制比较严格,这个浪费了好久时间,最后在网上找到了一个可以使用的封装好的POST方法,建议大家先自己试试,如果微信返回错误吗,就用这个吧,起码我测试微信这个接口的时候用postman测试返回的都是错误,而且一定要用JSON字符串,一定要是非常严格的JSON字符串。下面是这个方法:
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() 中有一个在配置文件中的参数给大家看下,其实就是微信接口链接:
C('WECHAT_PUBLIC_GET_TEMPORARY_TICKET') = https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=##TOKEN##
这个接口的返回值是:
{"ticket":"gQH47joAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL2taZ2Z3TVRtNzJXV1Brb3ZhYmJJAAIEZ23sUwMEmm3sUw==","expire_seconds":60,"url":"http:\/\/weixin.qq.com\/q\/kZgfwMTm72WWPkovabbI"}
其中ticket是让我们用来进行下一步调用的凭证,expire_seconds是二维码的有效期,url是我们生成的二维码扫描后打开的链接。所以如果我们自己实现了生成二维码的方法,就不用再进行下一步调用,我本人即在这一步就停止了,直接返回url的值,然后利用这个url的值生成二维码存在本地即可。PHP生成二维码可以使用phpqrcode,挺好用的。下一步也大致提一下:
3.2.2 获取二维码地址
请求方式: GET
接口:https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET
这个接口的返回值是一张图片,可以直接展示或者下载,我们有具体使用过,所以也不知道应该怎么展示。
3.3 用户扫描二维码之后发生的事情
3.3.1 扫描后发生了什么
上面提到了,用户扫描我们生成的临时二维码,如果用户未关注公众号,则首先会跳转到公众号的关注页面,点击关注后,会进入公众号的会话页面,同时会给我们设置的接口推送一个事件。如果用户已经关注了,用户微信会直接跳转到公众号会话页面,然后微信服务器会给我们设置的接口推送一个事件。
用户关注与否微信服务器给我们推送的事件是差不多的,只是新关注用户推送的事件中scene_id前面会加一个前缀。下面是微信公众平台文档的说明:
用户未关注时,进行关注后的事件推送
<xml><ToUserName><![CDATA[toUser]]></ToUserName> //开发者微信号 <FromUserName><![CDATA[FromUser]]></FromUserName> //发送者账号(openid) <CreateTime>123456789</CreateTime> //消息创建时间(整型) <MsgType><![CDATA[event]]></MsgType> //消息类型 event <Event><![CDATA[subscribe]]></Event> //事件类型(subscribe) <EventKey><![CDATA[qrscene_123123]]></EventKey> //事件KEY值,qrscene_为前缀,后面为二维码参数值 <Ticket><![CDATA[TICKET]]></Ticket> //二维码ticke值,可以用来换取二维码图片 </xml>
用户已关注时的事件推送
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> //开发者微信号 <FromUserName><![CDATA[FromUser]]></FromUserName> //发送者账号(openid) <CreateTime>123456789</CreateTime> //消息创建时间 <MsgType><![CDATA[event]]></MsgType> //消息类型event <Event><![CDATA[SCAN]]></Event> //事件类型 event <EventKey><![CDATA[SCENE_VALUE]]></EventKey> //事件key值,是一个32位无符号整数,即创建二维码时的二维码scene_id <Ticket><![CDATA[TICKET]]></Ticket> //二维码的ticke,可以用来换取二维码图片 </xml>
3.3.2 我们要做些什么
我们需要在自己填写的URL接口中接收这个事件,然后拿到我们需要的东西做我们想干的事儿。因为我要实现的功能比较简单,只需要拿到scene_id即可,因为这是我要展示给用户看的订单数据。下面是我写的接收和处理部分,比较简单,主要看一下应该怎么接收微信推送的事件:
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){ //已关注者扫描 $this->sendMessage($fromUsername, $EventKey); }else{ //未关注者关注后推送事件 $this->sendMessage($fromUsername, $keyArray[1]); } }
我没有使用其他参数,只是根据不同的推送事件拿到我想要的订单ID,然后这时候其实相当于你在这里用公众号的客服在跟扫码的这个用户对话,上段代码中调用的sendMessage()是使用客户账号给扫码用户发送一个图文消息,因为我在拿scen_id的同时也拿到了用户的openid,可以利用这个给用户发送消息。
下面是sendMessage()方法:
//给用户发送图文消息,点击跳转到报价页面 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,就是在组给用户发送的文字而已,需要注意$dataStr的格式,这里面要求JSON字符串比较严格,必须所有的字符串都用双引号括起来。微信接口对POST参数的限制真心严格。
下面是微信公众平台开发者文档中要求发送图文消息的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是用户点击这个消息之后打开的地址,这个时候我就组了一个自己网站的地址,是一个get请求地址,里面携带参数是用户的openid和订单id,这样用户点击开图文消息就可以看到自己刚才下单的内容了,因为需要在网页上展示用户的微信头像和昵称,所以我把openid也放到参数里,在页面加载前先拿到用户的个人信息和订单数据,再展示网页。这样流程:用户未登录下单 -> 生成微信二维码 -> 用户扫码关注公众号 -> 查看订单详细信息 就完成了。而且因为这个图文消息打开后的链接携带的参数是这个用户的额openid和其下单的订单ID,不管分享到哪儿,用什么浏览器打开都是可以访问的,且展示的也是这个用户的头像和昵称信息,这也是我要实现的一个效果。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。