国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home WeChat Applet WeChat Development WeChat development and implementation of custom menu code tutorial

WeChat development and implementation of custom menu code tutorial

May 15, 2017 pm 01:28 PM
php WeChat Custom menu

This article mainly introduces the complete process of custom menu development in WeChat in detail. It has certain reference value. Interested friends can refer to it

1. Overview of Custom Menu

Custom menus can help public accounts enrich their interfaces and allow users to understand the functions of public accounts better and faster. After opening the custom menu, the public account interface is as shown in the figure:

2. Apply for a custom menu

Personal subscription account Use Weibo authentication and enterprise subscription account to pass WeChat authentication; you can apply for custom menu qualifications

Service accounts have menu permissions by default.

3. Obtain AppId and AppSecert

AppId and AppSecret can be found in the Developer Center - Developer ID.


4. Obtain Access Token

Use appid and appsecert to obtain access token,

Interface

Forapi.weixin.qq.com/cgi-bi... mp;secret=APPSECRET

The program is implemented as follows

$appid = ""; 
$appsecret = ""; 
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret"; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_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); 
curl_close($ch); 
$jsoninfo = json_decode($output, true); 
$access_token = $jsoninfo["access_token"];

You can also directly enter the browser address column, splice out the address, and after execution, obtain the following data

The code is as follows:

{"access_token":"N2L7KXa084WvelONYjkJ_traBMCCvy_UKmpUUzlrQ0EA2yNp3Iz6eSUrRG0bhaR_viswd50vDuPkY5nG43d1gbm-olT2KRMxOsVE08RfeD9lvK9lMguNG9kpIkKGZEjIf8Jv2m9fFhf8bnNa-yQH3g",

The code is as follows:

"expires_in":7200}

The parameter description is as follows

N2L7KXa084WvelONYjkJ_traBMCCvy_UKmpUUzlrQ0EA2yNp3Iz6eSUrRG0bhaR_viswd50vDuPkY5nG43d1gbm-olT2KRMxOsVE08RfeD9lvK9lMguNG9kpIkKGZEjIf8Jv2m9fF hf8bnNa-yQH3g

is the access token.

Or use the official interface

Debugging

tool, the address is: https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type= %E8%87%AA%E5%AE%9A%E4%B9%89%E8%8F%9C%E5%8D%95&form=%E8%87%AA%E5%AE%9A%E4%B9%89% E8%8F%9C%E5%8D%95%E5%88%9B%E5%BB%BA%E6%8E%A5%E5%8F%A3%20/menu/create
Use web debugging Tool debugging custom menu interface

Click to check the problem and get

In this way, you also get the access token

5. Organization of menu content

Currently, custom menus include up to 3 first-level menus, and each first-level menu contains up to 5

Second-level menus

. The first-level menu can contain up to 4 Chinese characters, and the second-level menu can contain up to 7 Chinese characters. The extra parts will be replaced by "...". Please note that after creating a custom menu, it will take 24 hours for the WeChat client to display it due to the WeChat client's caching. It is recommended that when testing, you can try to unfollow the public account and follow it again, and you can see the effect after creation. Currently the custom menu interface can implement two types of

buttons

, as follows:

click:user After clicking the click type button, the WeChat server will push the message type event to the developer through the message interface (refer to the message interface guide), and bring the key
value filled in by the developer in the button. The developer can Interact with users through customized key values;
view: After the user clicks the view type button, the WeChat client will open and the developer will fill in the button The url value (that is, the web page link) can achieve the purpose of opening the web page. It is recommended to combine it with the web page's authorization to obtain the user's basic information interface to obtain the user's login personal information.
Interface call request description

http request method: POST (please use https protocol)

api.weixin.qq.com/cgi-bi...

_token=ACCESS_TOKEN Request example

{ 
 "button":[ 
  {  
   "type":"click", 
   "name":"今日歌曲", 
   "key":"V1001_TODAY_MUSIC" 
  }, 
  { 
   "type":"click", 
   "name":"歌手簡介", 
   "key":"V1001_TODAY_SINGER" 
  }, 
  { 
   "name":"菜單", 
   "sub_button":[ 
   {  
    "type":"view", 
    "name":"搜索", 
    "url":"http://www.soso.com/" 
   }, 
   { 
    "type":"view", 
    "name":"視頻", 
    "url":"http://v.qq.com/" 
   }, 
   { 
    "type":"click", 
    "name":"贊一下我們", 
    "key":"V1001_GOOD" 
   }] 
  }] 
}

Parameter description

Return result

When correct, the returned JSON data packet is as follows:

{"errcode":0,"errmsg":"ok"}

The returned JSON data packet in case of error is as follows (an example is invalid menu name length):

{"errcode":40018,"errmsg":"invalid button name size"}

6. Submit the menu content to the server

菜單的JSON結(jié)構(gòu)為

{"button": [{"name":"天氣預(yù)報","sub_button":[{"type":"click","name":"北京天氣","key":"天氣北 京"}, 
{"type":"click","name":"上海天氣","key":"天氣上海"}, 
{"type":"click","name":" 廣州天氣","key":"天氣廣州"},{"type":"click","name":"深圳天氣","key":"天氣深圳"}, 
{"type":"view","name":"本地天氣","url":"http://m.hao123.com/a/tianqi"}]}, 
{"name":"方倍工作室","sub_button":[{"type":"click","name":"公司簡 介","key":"company"}, 
{"type":"click","name":"趣味游戲","key":"游戲"}, {"type":"click","name":"講個笑話","key":"笑話"}]}]}

將以下代碼保存為menu.php,并且在瀏覽器中運行該文件(比如 127.0.0.1/menu.php),將直接向微信服務(wù)器提交菜單

php 
 
$access_token = ""; 
 
$jsonmenu = '{ 
  "button":[ 
  { 
   "name":"天氣預(yù)報", 
   "sub_button":[ 
   { 
    "type":"click", 
    "name":"北京天氣", 
    "key":"天氣北京" 
   }, 
   { 
    "type":"click", 
    "name":"上海天氣", 
    "key":"天氣上海" 
   }, 
   { 
    "type":"click", 
    "name":"廣州天氣", 
    "key":"天氣廣州" 
   }, 
   { 
    "type":"click", 
    "name":"深圳天氣", 
    "key":"天氣深圳" 
   }, 
   { 
    "type":"view", 
    "name":"本地天氣", 
    "url":"http://m.hao123.com/a/tianqi" 
   }] 
  
 
  }, 
  { 
   "name":"瑞雪", 
   "sub_button":[ 
   { 
    "type":"click", 
    "name":"公司簡介", 
    "key":"company" 
   }, 
   { 
    "type":"click", 
    "name":"趣味游戲", 
    "key":"游戲" 
   }, 
   { 
    "type":"click", 
    "name":"講個笑話", 
    "key":"笑話" 
   }] 
  
 
  }] 
}'; 
 
 
$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; 
}
?>

或者使用官方的調(diào)試接口 使用網(wǎng)頁調(diào)試工具調(diào)試該接口

提交成功后,重新關(guān)注后即可看到菜單。菜單效果類似如下:

七、響應(yīng)菜單點擊事件

在消息接口中處理event事件,其中的click代表菜單點擊,通過響應(yīng)菜單結(jié)構(gòu)中的key值回應(yīng)消息,view事件無須響應(yīng),將直接跳轉(zhuǎn)過去

define("TOKEN", "weixin"); 
 
$wechatObj = new wechatCallbackapiTest(); 
if (!isset($_GET['echostr'])) { 
  $wechatObj->responseMsg(); 
}else{ 
  $wechatObj->valid(); 
} 
 
class wechatCallbackapiTest 
{ 
  public function valid() 
  { 
    $echoStr = $_GET["echostr"]; 
    if($this->checkSignature()){ 
      echo $echoStr; 
      exit; 
    } 
 } 
 
  private function checkSignature() 
  { 
    $signature = $_GET["signature"]; 
   $timestamp = $_GET["timestamp"]; 
    $nonce = $_GET["nonce"]; 
 
   $token = TOKEN; 
    $tmpArr = array($token, $timestamp, $nonce); 
    sort($tmpArr); 
    $tmpStr = implode( $tmpArr ); 
    $tmpStr = sha1( $tmpStr ); 
 
    if( $tmpStr == $signature ){ 
      return true; 
    }else{ 
      return false; 
    } 
  } 
 
  public function responseMsg() 
  { 
    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 
    if (!empty($postStr)){ 
      $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 
    $RX_TYPE = trim($postObj->MsgType); 
 
     switch ($RX_TYPE) 
      { 
        case "text": 
          $resultStr = $this->receiveText($postObj); 
          break; 
        case "event": 
         $resultStr = $this->receiveEvent($postObj); 
          break; 
        default: 
          $resultStr = ""; 
         break; 
      } 
      echo $resultStr; 
    }else { 
      echo ""; 
     exit; 
    } 
  } 
 
  private function receiveText($object) 
  { 
    $funcFlag = 0; 
    $contentStr = "你發(fā)送的內(nèi)容為:".$object->Content; 
    $resultStr = $this->transmitText($object, $contentStr, $funcFlag); 
    return $resultStr; 
  } 
   
  private function receiveEvent($object) 
  { 
    $contentStr = ""; 
    switch ($object->Event) 
    { 
      case "subscribe": 
        $contentStr = "歡迎洋洋博客"; 
      case "unsubscribe": 
        break; 
      case "CLICK": 
        switch ($object->EventKey) 
        { 
          case "company": 
            $contentStr[] = array("Title" =>"公司簡介",  
            "Description" =>"洋洋的博客",  
            "PicUrl" =>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg",  
            "Url" =>"weixin://addfriend/pondbaystudio"); 
            break; 
          default: 
            $contentStr[] = array("Title" =>"默認菜單回復(fù)",  
            "Description" =>"您正在使用的是<span style="font-family: Arial, Helvetica, sans-serif;">洋洋的博客</span><span style="font-family: Arial, Helvetica, sans-serif;">", </span> 
            "PicUrl" =>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg",  
            "Url" =>"weixin://addfriend/pondbaystudio"); 
            break; 
        } 
        break; 
      default: 
        break;    
 
    } 
    if (is_array($contentStr)){ 
      $resultStr = $this->transmitNews($object, $contentStr); 
    }else{ 
      $resultStr = $this->transmitText($object, $contentStr); 
   } 
    return $resultStr; 
  } 
 
  private function transmitText($object, $content, $funcFlag = 0) 
  { 
    $textTpl = "<xml> 
<ToUserName><![CDATA[%s]]></ToUserName> 
<FromUserName><![CDATA[%s]]></FromUserName> 
<CreateTime>%s</CreateTime> 
<MsgType><![CDATA[text]]></MsgType> 
<Content><![CDATA[%s]]></Content> 
<FuncFlag>%d</FuncFlag> 
</xml>"; 
    $resultStr = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(), $content, $funcFlag); 
    return $resultStr; 
  } 
 
  private function transmitNews($object, $arr_item, $funcFlag = 0) 
  { 
    //首條標題28字,其他標題39字 
    if(!is_array($arr_item)) 
      return; 
 
    $itemTpl = "  <item> 
    <Title><![CDATA[%s]]></Title> 
    <Description><![CDATA[%s]]></Description> 
    <PicUrl><![CDATA[%s]]></PicUrl> 
    <Url><![CDATA[%s]]></Url> 
  </item> 
"; 
    $item_str = ""; 
    foreach ($arr_item as $item) 
      $item_str .= sprintf($itemTpl, $item[&#39;Title&#39;], $item[&#39;Description&#39;], $item[&#39;PicUrl&#39;], $item[&#39;Url&#39;]); 
 
    $newsTpl = "<xml> 
<ToUserName><![CDATA[%s]]></ToUserName> 
<FromUserName><![CDATA[%s]]></FromUserName> 
<CreateTime>%s</CreateTime> 
<MsgType><![CDATA[news]]></MsgType> 
<Content><![CDATA[]]></Content> 
<ArticleCount>%s</ArticleCount> 
<Articles> 
$item_str</Articles> 
<FuncFlag>%s</FuncFlag> 
</xml>"; 
 
   $resultStr = sprintf($newsTpl, $object->FromUserName, $object->ToUserName, time(), count($arr_item), $funcFlag); 
    return $resultStr; 
  } 
} 
?>

八、菜單中獲取OpenID

由于菜單中只能填寫固定的url地址,對于想要菜單中獲取用戶的OpenID的情況,可以使用OAuth2.0授權(quán)的方式來實現(xiàn)。

URL中填寫的地址為一個固定的回調(diào)地址。原理方法可以參考 微信公眾平臺開發(fā)(99) 自定義菜單獲取OpenID

<?php 
/* 
  洋洋的博客 
*/ 
 
define("TOKEN", "weixin"); 
$wechatObj = new wechatCallbackapiTest(); 
if (isset($_GET[&#39;echostr&#39;])) { 
  $wechatObj->valid(); 
}else{ 
  $wechatObj->responseMsg(); 
} 
 
class wechatCallbackapiTest 
{ 
  public function valid() 
  { 
    $echoStr = $_GET["echostr"]; 
    if($this->checkSignature()){ 
      header(&#39;content-type:text&#39;); 
      echo $echoStr; 
      exit; 
    } 
  } 
 
  private function checkSignature() 
  { 
    $signature = $_GET["signature"]; 
    $timestamp = $_GET["timestamp"]; 
    $nonce = $_GET["nonce"]; 
 
    $token = TOKEN; 
    $tmpArr = array($token, $timestamp, $nonce); 
    sort($tmpArr, SORT_STRING); 
    $tmpStr = implode( $tmpArr ); 
    $tmpStr = sha1( $tmpStr ); 
 
    if( $tmpStr == $signature ){ 
      return true; 
    }else{ 
      return false; 
    } 
  } 
 
  public function responseMsg() 
  { 
    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 
 
    if (!empty($postStr)){ 
      $postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA); 
      $fromUsername = $postObj->FromUserName; 
      $toUsername = $postObj->ToUserName; 
      $keyword = trim($postObj->Content); 
      $time = time(); 
      $textTpl = "<xml> 
            <ToUserName><![CDATA[%s]]></ToUserName> 
            <FromUserName><![CDATA[%s]]></FromUserName> 
            <CreateTime>%s</CreateTime> 
            <MsgType><![CDATA[%s]]></MsgType> 
            <Content><![CDATA[%s]]></Content> 
            <FuncFlag>0</FuncFlag> 
            </xml>"; 
      if($keyword == "?" || $keyword == "?") 
      { 
        $msgType = "text"; 
        $contentStr = &#39;當(dāng)前時間是:&#39;.date("Y-m-d H:i:s",time()); 
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); 
        echo $resultStr; 
      } 
    }else{ 
      echo ""; 
      exit; 
    } 
  } 
} 
?>

【相關(guān)推薦】

1. 特別推薦“php程序員工具箱”V0.1版本下載

2. 微信公眾號平臺源碼下載

3. 阿貍子訂單系統(tǒng)源碼下載

The above is the detailed content of WeChat development and implementation of custom menu code tutorial. 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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

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)

Hot Topics

PHP Tutorial
1502
276
How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization How to use PHP combined with AI to achieve text error correction PHP syntax detection and optimization Jul 25, 2025 pm 08:57 PM

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Beyond the LAMP Stack: PHP's Role in Modern Enterprise Architecture Jul 27, 2025 am 04:31 AM

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Object-Relational Mapping (ORM) Performance Tuning in PHP Object-Relational Mapping (ORM) Performance Tuning in PHP Jul 29, 2025 am 05:00 AM

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

Building Resilient Microservices with PHP and RabbitMQ Building Resilient Microservices with PHP and RabbitMQ Jul 27, 2025 am 04:32 AM

To build a flexible PHP microservice, you need to use RabbitMQ to achieve asynchronous communication, 1. Decouple the service through message queues to avoid cascade failures; 2. Configure persistent queues, persistent messages, release confirmation and manual ACK to ensure reliability; 3. Use exponential backoff retry, TTL and dead letter queue security processing failures; 4. Use tools such as supervisord to protect consumer processes and enable heartbeat mechanisms to ensure service health; and ultimately realize the ability of the system to continuously operate in failures.

python run shell command example python run shell command example Jul 26, 2025 am 07:50 AM

Use subprocess.run() to safely execute shell commands and capture output. It is recommended to pass parameters in lists to avoid injection risks; 2. When shell characteristics are required, you can set shell=True, but beware of command injection; 3. Use subprocess.Popen to realize real-time output processing; 4. Set check=True to throw exceptions when the command fails; 5. You can directly call chains to obtain output in a simple scenario; you should give priority to subprocess.run() in daily life to avoid using os.system() or deprecated modules. The above methods override the core usage of executing shell commands in Python.

Creating Production-Ready Docker Environments for PHP Creating Production-Ready Docker Environments for PHP Jul 27, 2025 am 04:32 AM

Using the correct PHP basic image and configuring a secure, performance-optimized Docker environment is the key to achieving production ready. 1. Select php:8.3-fpm-alpine as the basic image to reduce the attack surface and improve performance; 2. Disable dangerous functions through custom php.ini, turn off error display, and enable Opcache and JIT to enhance security and performance; 3. Use Nginx as the reverse proxy to restrict access to sensitive files and correctly forward PHP requests to PHP-FPM; 4. Use multi-stage optimization images to remove development dependencies, and set up non-root users to run containers; 5. Optional Supervisord to manage multiple processes such as cron; 6. Verify that no sensitive information leakage before deployment

VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

A Deep Dive into PHP's Internal Garbage Collection Mechanism A Deep Dive into PHP's Internal Garbage Collection Mechanism Jul 28, 2025 am 04:44 AM

PHP's garbage collection mechanism is based on reference counting, but circular references need to be processed by a periodic circular garbage collector; 1. Reference count releases memory immediately when there is no reference to the variable; 2. Reference reference causes memory to be unable to be automatically released, and it depends on GC to detect and clean it; 3. GC is triggered when the "possible root" zval reaches the threshold or manually calls gc_collect_cycles(); 4. Long-term running PHP applications should monitor gc_status() and call gc_collect_cycles() in time to avoid memory leakage; 5. Best practices include avoiding circular references, using gc_disable() to optimize performance key areas, and dereference objects through the ORM's clear() method.

See all articles