Home > WeChat Applet > WeChat Development > Detailed explanation of the instructions for using php WeChat to develop QR codes with parameters

Detailed explanation of the instructions for using php WeChat to develop QR codes with parameters

高洛峰
Release: 2017-03-16 15:00:41
Original
1698 people have browsed it

This 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.

Detailed explanation of the instructions for using php WeChat to develop QR codes with parameters

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:

When the user scans this QR code, if the user follows the official account, the user It will directly enter the conversation page with the official account. The WeChat server will push a message to the server URL we set in the previous step, which can carry a custom parameter. If the user does not follow the official account, the user will first jump to the official account follow page. After the user clicks to follow, he will directly enter the conversation page of the official account. At this time, the WeChat server will also push an event message to the URL we set, carrying We customize parameters, and we can control the next action based on this parameter and event type.


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'];        //前面不用管,是我数据库相应设置

 if (time() < $expireTime){    //access_token未过期
  return $wechatInfo[&#39;PUBLIC_WECHAT_ACCESSTOKEN&#39;][&#39;conf_value&#39;];
 }else{         //access_token过期,重新获取
  $baseUrl = C(&#39;WECHAT_PUBLIC_GET_ACCESS_TOKEN&#39;);
  $url = str_replace("##APPSECRET##", $wechatInfo[&#39;PUBLIC_WECHAT_APPSECRET&#39;][&#39;conf_value&#39;], str_replace("##APPID##", $wechatInfo[&#39;PUBLIC_WECHAT_APPID&#39;][&#39;conf_value&#39;], $baseUrl));
  $result = file_get_contents($url);
  $result = json_decode($result, true);

  if (array_key_exists(&#39;errorcode&#39;, $result)){  //失败重试一次
   return false;
  }else{
   M(&#39;wechat_info&#39;)->where(array(&#39;conf_name&#39; => &#39;PUBLIC_WECHAT_ACCESSTOKEN&#39;))->save(array(&#39;conf_value&#39; => $result[&#39;access_token&#39;]));
   M(&#39;wechat_info&#39;)->where(array(&#39;conf_name&#39; => &#39;PUBLIC_WECHAT_ACCESSTOKEN_EXPIRES&#39;))->save(array(&#39;conf_value&#39; => time()+$result[&#39;expires_in&#39;]-200));
   return $result[&#39;access_token&#39;];
  }
 }
}
Copy after login

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:

//创建临时二维码
function getTemporaryQrcode($orderId){
 $accessToken = getWechatAccessToken();
 $url = str_replace("##TOKEN##", $accessToken, C(&#39;WECHAT_PUBLIC_GET_TEMPORARY_TICKET&#39;));
 $qrcode = &#39;{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": &#39;.$orderId.&#39;}}}&#39;;
 $result = api_notice_increment($url, $qrcode);
 $result = json_decode($result, true);
 return urldecode($result[&#39;url&#39;]);
}
Copy after login

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, &#39;Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)&#39;);
 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;
 }

}
Copy after login

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
这个接口的返回值是一张图片,可以直接展示或者下载,我们有具体使用过,所以也不知道应该怎么展示。

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>
Copy after login

用户已关注时的事件推送

<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>
Copy after login

3.3.2 我们要做些什么

我们需要在自己填写的URL接口中接收这个事件,然后拿到我们需要的东西做我们想干的事儿。因为我要实现的功能比较简单,只需要拿到scene_id即可,因为这是我要展示给用户看的订单数据。下面是我写的接收和处理部分,比较简单,主要看一下应该怎么接收微信推送的事件:

public function urlRedirect(){
  $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
  $postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, 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]);
  }
 }
Copy after login

我没有使用其他参数,只是根据不同的推送事件拿到我想要的订单ID,然后这时候其实相当于你在这里用公众号的客服在跟扫码的这个用户对话,上段代码中调用的sendMessage()是使用客户账号给扫码用户发送一个图文消息,因为我在拿scen_id的同时也拿到了用户的openid,可以利用这个给用户发送消息

下面是sendMessage()方法:

//给用户发送图文消息,点击跳转到报价页面
 public function sendMessage($openid,$orderId){
  $url = str_replace(&#39;##TOKEN##&#39;, getWechatAccessToken(), C(&#39;WECHAT_SEND_MESSAGE&#39;));
  $redirectUrl = str_replace("##ORDERID##", $orderId, str_replace("##OPENID##", $openid, C(&#39;WECHAT_REDIRECT_URL_PRE&#39;)));
  $orderInfo = M(&#39;order&#39;)->where(array(&#39;orderid&#39; => $orderId))->field(array(&#39;totalMoney&#39;, &#39;savedMoney&#39;, &#39;roomarea&#39;))->find();
  $description = str_replace("##ROOMAREA##", intval($orderInfo[&#39;roomarea&#39;] * 1.25), C(&#39;WECHAT_MESSAGE_BRIEF&#39;));
  $description = str_replace("##TOTALBUDGET##", $orderInfo[&#39;totalMoney&#39;], $description);
  $description = str_replace("##MARKETBUDGET##", $orderInfo[&#39;totalMoney&#39;]+$orderInfo[&#39;savedMoney&#39;], $description);
  $description = str_replace("##SAVEMONEY##", $orderInfo[&#39;savedMoney&#39;], $description);
  $dataStr = &#39;{"touser":"&#39; . $openid . &#39;","msgtype":"news","news":{"articles":[{"title":"&#39; . C(&#39;WECHAT_MESSAGE_TITLE&#39;) .
   &#39;","description":"&#39; . $description . &#39;","url":"&#39; . $redirectUrl . &#39;","picurl":"&#39; . C(&#39;WECHAT_MESSAGE_PICURL&#39;) . &#39;""}]}}&#39;;
  api_notice_increment($url, $dataStr);
 }
Copy after login

其中 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"
   }
   ]
 }
}
Copy after login

其中url是用户点击这个消息之后打开的地址,这个时候我就组了一个自己网站的地址,是一个get请求地址,里面携带参数是用户的openid和订单id,这样用户点击开图文消息就可以看到自己刚才下单的内容了,因为需要在网页上展示用户的微信头像和昵称,所以我把openid也放到参数里,在页面加载前先拿到用户的个人信息和订单数据,再展示网页。这样流程:用户未登录下单 -> 生成微信二维码 -> 用户扫码关注公众号 -> 查看订单详细信息 就完成了。而且因为这个图文消息打开后的链接携带的参数是这个用户的额openid和其下单的订单ID,不管分享到哪儿,用什么浏览器打开都是可以访问的,且展示的也是这个用户的头像和昵称信息,这也是我要实现的一个效果。


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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template