Home Backend Development PHP Tutorial Detailed explanation of PHP WeChat custom menu interface, customer service interface, and QR code usage code

Detailed explanation of PHP WeChat custom menu interface, customer service interface, and QR code usage code

Jul 03, 2017 am 10:37 AM
php customer service customize

How to call the WeChat advanced interface

The difference between the WeChat advanced interface and the WeChat ordinary interface

The background server can Calling WeChat interfaces to communicate messages with WeChat users is calling WeChat interfaces. These interfaces are basic interfaces, and you can call them without any payment or identity authentication. However, there are some advanced interfaces. Your WeChat official account must have certain permissions, such as passing WeChat authentication to call custom menu, WeChat payment and other advanced functions.
However, the test account system of WeChat public accounts can apply these advanced interfaces (except for interfaces involving transactions such as WeChat payment).

Call of WeChat advanced interface

#Call of WeChat advanced interface requires calling a token_access interface first. Only by calling this interface first can other advanced interfaces be called. interface.
As follows: Schematic diagram of connecting the advanced interface


Calling token_access requires appID and appsecreset (already used in WeChat public account platform development (1) Tell the origin of the two)

The calling code is as follows

<?php
$appid = "wxbad0b4x543aa0b5e";
$appsecret = "ed222a84da15cd24c4bdfa5d9adbabf2";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
//下面是一个cURL会话过程,通过这个会话可以返回一段字符串{"access_token":"NU7Kr6v9L9TQaqm5NE3OTPctTZx797Wxw4Snd2WL2HHBqLCiXlDVOw2l-Se0I-WmOLLniAYLAwzhbYhXNjb"}
这就是我们要获得的Access Token了。在调用高级功能接口的时候就靠它。这个过程用的时候直接引用就好,不需要深究,这个cURL系统相关函数有点多而且复杂。

$ch = curl_init();//初始化
curl_setopt($ch, CURLOPT_URL, $url);//与url建立对话
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); //进行配置
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //进行配置
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//进行配置
$output = curl_exec($ch);//执行对话,获取接口数据Access Token
curl_close($ch);//关闭会话
$jsoninfo = json_decode($output, true);//解码接口数据,将json格式字符串转换成php变量或数组。默认是变量,加true后是数组。
$access_token = $jsoninfo["access_token"];

?>
Copy after login

Calling the WeChat advanced interface

1), calling the custom menu function

 //创建一个自定义菜单的json字符串
 $jsonmenu = &#39;{
  "button":[
  {
   "name":"关于我们",
   "sub_button":[
   {
    "type":"click",
    "name":"公司简介",
    "key":"公司简介"
   },
   {
    "type":"click",
    "name":"社会责任",
    "key":"社会责任"
   },
   {
    "type":"click",
    "name":"联系我们",
    "key":"联系我们"
   }]
  },
  {
   "name":"产品服务",
   "sub_button":[
   {
    "type":"click",
    "name":"微信平台",
    "key":"微信平台"
   },
   {
    "type":"click",
    "name":"微博应用",
    "key":"微博应用"
   },
   {
    "type":"click",
    "name":"手机网站",
    "key":"手机网站"
   }]
  },
  {
   "name":"技术支持",
   "sub_button":[
   {
    "type":"click",
    "name":"文档下载",
    "key":"文档下载"
   },
   {
    "type":"click",
    "name":"技术社区",
    "key":"技术社区"
   },
   {
    "type":"click",
    "name":"服务热线",
    "key":"服务热线"
   }]
  }]
 }&#39;;

 $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;//接口地址
$result = https_request($url, $jsonmenu);//与接口建立会话
var_dump($result);

function https_request($url,$data = null){
 $curl = curl_init();
 curl_setopt($curl, CURLOPT_URL, $url);
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
 if (!empty($data)){
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
 }
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 $output = curl_exec($curl);
 curl_close($curl);
 return $output;
}
//把这段代码加入到上面的调用Access Token接口的代码中就可以实现在微信公众号界面添加菜单的功能。
Copy after login

After we add a menu to the WeChat official account, how to set the corresponding effect when clicking on the menu?
This involves another XML type of data transfer:

<xml>
<ToUserName><![CDATA[gh_82479813ed64]]></ToUserName>
<FromUserName><![CDATA[ojpX_jig-gyi3_Q9fHXQ4rdHniQs]]></FromUserName>
<CreateTime>1392297442</CreateTime>
<MsgType><![CDATA[event]]></MsgType>
<Event><![CDATA[CLICK]]></Event>
<EventKey><![CDATA[公司简介]]></EventKey>
</xml>
//上面是点击click菜单的数据传递类型,数据会发送给后台服务器,然后服务器做出响应。
Copy after login

There are many menu types, and the XML types are different. For details, you can view the corresponding documents on the WeChat public account platform.

*What I want to explain here is that as long as you have the appID and appsecret of the WeChat official account, you can enter the WeChat server to call the corresponding function by running this php code in any server space. It does not have to be run under a server with token verification. Token verification is for the backend server to determine whether the data source is from the WeChat server, and has little to do with calling the high-level interface of the WeChat server.
The php file must be run on the server to have any effect.

The calling of other advanced interfaces is the same as calling the custom menu.

2), call the customer service interface

When a WeChat user actively sends a message to a WeChat public account (including sending a message, clicking on a custom menu click event, subscribing to an event, and scanning a QR code , payment success event) WeChat will push the message data to the developer. Developers can call customer service interface messages within a period of time and send messages to users by posting a JSON data packet.

The code is as follows:

$access_token = "nFX6GFsspSLBKJLgMQ3kj1YM8_FchRE7vE2ZOIlmfiCOQntZKnBwuOen2GCBpFHBYS4QLGX9fGoVfA36tftME2sRiYsKPzgGQKU-ygU7x8cgy_1tlQ4n1mhSumwQEGy6PK6rdTdo8O8GROuGE3Hiag";
$openid = "o7Lp5t6n59DeX3U0C7Kric9qEx-Q";//微信用户都有一个openID
Copy after login

The figure below shows how to obtain openID.


##

$data = &#39;{
 "touser":"&#39;.$openid.&#39;",
 "msgtype":"text",
 "text":
 {
   "content":"Hello World"
 }
}&#39;;//通过基础消息接口发送的数据是XML格式的,但是调用客服接口发送的数据是json数据格式,更易传输。 
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
$result = https_request($url,$data);
var_dump($result);

function https_request($url,$data)
{
 $curl = curl_init();
 curl_setopt($curl, CURLOPT_URL, $url); 
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
 curl_setopt($curl, CURLOPT_POST, 1);
 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 $result = curl_exec($curl);
 if (curl_errno($curl)) {
  return &#39;Errno&#39;.curl_error($curl);
 }
 curl_close($curl);
 return $result;
}
Copy after login

Customer service interface to send graphic messages, music messages, video messages, please refer to the development on the WeChat public platform for specific formats Help documentation.

Customer service interface can be mixed with message interface.

Everyone here may not understand why we need such a customer service interface since we can directly send XML data to users through the passive response message interface. It can be understood that a passive response message is a one-time reply to the same message only once. If you enter a singer's name into a music platform, the message sent through passive response will always reply you with the same song. However, you can reply to different songs each time through the customer service interface, which involves

MySQL database.

A little simpler, a WeChat public platform for viewing express delivery including the address. Every time you enter the same order number, the background can reply to the location of the order each time (different responses can be made for the same text), just like a manual reply. This is the customer service interface.

3), Generate QR code interface

There are two types of QR codes, namely temporary QR code eh and permanent QR code. The former has an expiration time of up to 1800s. .

You need to call 3 interfaces to generate a QR code,
The first is access_token
The second is to generate a ticket interface
The third is to exchange tickets generated through the second interface for 2 QR code picture.

$access_token = " xDx0pD_ZvXkHM3oeu5oGjDt1_9HxlA-9g0vtR6MZ-v4r7MpvZYC4ee4OxN97Lr4irkPKE94tzBUhpZG_OvqAC3D3XaWJIGIn0eeIZnfaofO1C3LNzGphd_rEv3pIimsW9lO-4FOw6D44T3sNsQ5yXQ";//假定获取的ACCESS TOKEN为这段代码。

//临时二维码
$qrcode = &#39;{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 10000}}}&#39;;
//永久二维码
$qrcode = &#39;{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 1000}}}&#39;;

$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$access_token";//创建ticket接口
$result = https_request($url,$qrcode);
$jsoninfo = json_decode($result, true);
$ticket = $jsoninfo["ticket"];

function https_request($url, $data = null){
 $curl = curl_init();
 curl_setopt($curl, CURLOPT_URL, $url);
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
 if (!empty($data)){
  curl_setopt($curl, CURLOPT_POST, 1);
  curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
 }
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 $output = curl_exec($curl);
 curl_close($curl);
 return $output;
}


$ticket = "gQHi8DoAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL0UweTNxNi1sdlA3RklyRnNKbUFvAAIELdnUUgMEAAAAAA==";//获取ticket的字符串

$url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket);//ticket对面二维码图片代码。
$imageInfo = downloadWeixinFile($url);

$filename = "qrcode.jpg";
$local_file = fopen($filename, &#39;w&#39;);
if (false !== $local_file){
 if (false !== fwrite($local_file, $imageInfo["body"])) {
  fclose($local_file);
 }
}

function downloadWeixinFile($url)
{
 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_HEADER, 0); 
 curl_setopt($ch, CURLOPT_NOBODY, 0); //只取body头
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 $package = curl_exec($ch);
 $httpinfo = curl_getinfo($ch);
 curl_close($ch);
 return array_merge(array(&#39;body&#39; => $package), array(&#39;header&#39; => $httpinfo)); 
}
Copy after login
Run this code in the server space, and the browser will generate a QR code image.

Obtain non-WeChat functional interfaces, such as obtaining traffic information and weather forecast.

The above is the detailed content of Detailed explanation of PHP WeChat custom menu interface, customer service interface, and QR code usage code. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles