SoFunction
Updated on 2025-03-10

How to create custom menus using PHP on WeChat

Before using a common interface, you need to do the following two steps:
1. Have a WeChat public account and obtain the appid and appsecret (apply for internal testing qualification on the public platform, and you can obtain it after the review is approved)
2. Obtain access_token through the access credential interface
Notice:
access_token is a ticket for third-party access to API resources;
access_token corresponds to the public account being the globally unique ticket. Repeated acquisition will cause the access_token you obtained last time to be invalid.

Visit the following address (note that you replace your appid and secret):

/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

Then you can see the return information in the browser:
{"access_token":"This is your access_token","expires_in":7200}

Create a custom menu:

<?php
header("Content-type: text/html; charset=utf-8");
define("ACCESS_TOKEN", "Fill in the access_token you obtained above here");


//Create menufunction createMenu($data){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "/cgi-bin/menu/create?access_token=".ACCESS_TOKEN);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
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)) {
 return curl_error($ch);
}

curl_close($ch);
return $tmpInfo;

}

//Get menufunction getMenu(){
return file_get_contents("/cgi-bin/menu/get?access_token=".ACCESS_TOKEN);
}

//Delete the menufunction deleteMenu(){
return file_get_contents("/cgi-bin/menu/delete?access_token=".ACCESS_TOKEN);
}





$data = '{
   "button":[
   {
     "type":"click",
     "name":"front page",
     "key":"home"
   },
   {
      "type":"click",
      "name":"Introduction",
      "key":"introduct"
   },
   {
      "name":"menu",
      "sub_button":[
      {
        "type":"click",
        "name":"hello word",
        "key":"V1001_HELLO_WORLD"
      },
      {
        "type":"click",
        "name":"Praise us",
        "key":"V1001_GOOD"
      }]
    }]
}';




echo createMenu($data);
//echo getMenu();
//echo deleteMenu();

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.