search
HomeBackend DevelopmentPHP TutorialPHP WeChat advanced interface calling method (custom menu interface, customer service interface, QR code)_php example

How to call WeChat advanced interface

The difference between WeChat advanced interface and WeChat ordinary interface

The backend server can call the WeChat interface to communicate with WeChat users. Such behavior is calling the WeChat interface. These interfaces are basic interfaces. 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 advanced functions such as custom menus and WeChat payment.
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

To call the WeChat advanced interface, you need to call a token_access interface first. Only by calling this interface first can you call other advanced interfaces.
As shown below: Schematic diagram of connecting advanced interface


Calling token_access requires appID and appsecreset (the origin of these two has been described in WeChat public account platform development (1))

The calling code is as follows

<&#63;php
$appid = "wxbad0b4x543aa0b5e";
$appsecret = "ed222a84da15cd24c4bdfa5d9adbabf2";
$url = "https://api.weixin.qq.com/cgi-bin/token&#63;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"];

&#63;>

Call WeChat advanced interface

1), call the custom menu function

 //创建一个自定义菜单的json字符串
 $jsonmenu = '{
  "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":"服务热线"
   }]
  }]
 }';

 $url = "https://api.weixin.qq.com/cgi-bin/menu/create&#63;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接口的代码中就可以实现在微信公众号界面添加菜单的功能。

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菜单的数据传递类型,数据会发送给后台服务器,然后服务器做出响应。

There are many menu types, and the xml types are different. For details, you can view the corresponding documents on the WeChat official 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 run this php code in any server space to enter the WeChat server to call the corresponding function. It does not have to be on a server that has undergone token verification. run below. 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.

Calling other advanced interfaces is the same as calling custom menus.

2), call customer service interface

When WeChat users actively send messages to WeChat public accounts (including sending messages, clicking custom menu click events, subscription events, scanning QR codes, and payment success events) WeChat will push the message data to developers. Developers can call customer service interface messages within a period of time and send messages to users by posting a JSON data packet.

Copy code The code is as follows:
$access_token = "nFX6GFsspSLBKJLgMQ3kj1YM8_FchRE7vE2ZOIlmfiCOQntZKnBwuOen2GCBpFHBYS4QLGX9fGoVfA36tftME2sRiYsKPzgG QKU-ygU7x8cgy_1tlQ4n1mhSumwQEGy6PK6rdTdo8O8GROuGE3Hiag";
$openid = "o7Lp5t6n59DeX3U0C7Kric9qEx-Q"; //WeChat users all have an openID

The picture below shows how to obtain openID.

$data = '{
 "touser":"'.$openid.'",
 "msgtype":"text",
 "text":
 {
   "content":"Hello World"
 }
}';//通过基础消息接口发送的数据是XML格式的,但是调用客服接口发送的数据是json数据格式,更易传输。 
$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send&#63;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 'Errno'.curl_error($curl);
 }
 curl_close($curl);
 return $result;
}

For the specific format of sending graphic messages, music messages, and video messages through the customer service interface, please refer to the development help document on the WeChat public platform.
The customer service interface can be mixed with the message interface.

You may not understand here that since you can directly send XML data to users through the passive response message interface, why do you need such a customer service 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, through the customer service interface, you can reply to different songs each time, which involves the MySQL database.

A little simpler, a WeChat public platform for checking express delivery including 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.
To generate a QR code you need to call 3 interfaces,
The first one is access_token
The second one is to generate ticket interface
The third one is to exchange the ticket generated through the second interface for the QR code image.

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

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

$url = "https://api.weixin.qq.com/cgi-bin/qrcode/create&#63;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&#63;ticket=".urlencode($ticket);//ticket对面二维码图片代码。
$imageInfo = downloadWeixinFile($url);

$filename = "qrcode.jpg";
$local_file = fopen($filename, 'w');
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('body' => $package), array('header' => $httpinfo)); 
}

Run this code in the server space, and the browser will generate a QR code image.

Get non-WeChat functional interfaces, such as getting traffic information and weather forecast.

The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope that everyone will support Script Home.

Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.