php微信開發自訂選單的方法分享

墨辰丷
發布: 2023-03-29 08:02:02
原創
1388 人瀏覽過

這篇文章主要為大家詳細介紹了php微信開發自訂選單,具有一定的參考價值,有興趣的小夥伴們可以參考一下

目前微信服務號自訂選單最多包含3個一級菜單,每個一級菜單最多包含5個二級菜單。一級選單最多4個漢字,二級選單最多7個漢字,多出來的部分將會以「...」取代。請注意,創建自訂選單後,由於微信客戶端緩存,需要24小時微信客戶端才會展現出來。建議測試時可以嘗試取消關注公眾帳號後再次關注,則可以看到創建後的效果。

目前自訂選單介面可實現兩種類型按鈕,如下:
 click:使用者點擊click類型按鈕後,微信伺服器會透過訊息接口推播訊息類型為event 的結構給開發者(參考訊息介面指南),並且帶上按鈕中開發者填入的key值,開發者可以透過自訂的key值與使用者進行互動;
view:
使用者點擊view類型按鈕後,微信用戶端將會開啟開發者在按鈕中填寫的url值 (即網頁連結),達到開啟網頁的目的,建議與網頁授權取得使用者基本資訊介面結合,取得使用者的登入個人資訊。

介面呼叫請求說明http請求方式:POST(請使用https協定) https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
請求範例(JSON資料請使用UTF-8編碼)

 {
 "button":[
  {"type":"click","name":"我的信息","sub_button":[
   {"type":"click","name":"拇指查询","key":"BUTTON_1"},
  {"type":"click","name":"拇指请假","key":"BUTTON_2"},
  {"type":"view","name":"工号绑定","url":"http://XXXXXXXXXXXXXXXXX"}]
 },
  {"type":"click","name":"业务流程","key":"BUTTON_3"},
  {"name":"员工建议","sub_button":[
   {"type":"view","name":"思想火花","url":"http://XXXXXXXXXXXXXXXXXX"},
   {"type":"view","name":"奖品兑换","url":"http://XXXXXXXXXXXXXXXXXX"},
   {"type":"click","name":"赞一下我们","key":"BUTTON_ZAN"}]
  }
 ]
}
登入後複製

參數說明

#傳回結果 
正確時的回傳JSON數據套件如下:
 {"errcode":0,"errmsg":"ok"} 
錯誤時的回傳JSON封包如下(範例為無效選單名長度):
 {"errcode":40018 ,"errmsg":"invalid button name size"} 

以下是範例程式碼(PHP)。

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <meta name="author" content="Chris Mao" />
 </head>
 <body>
 <?php
  $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

  $output = curl_exec($ch);
  curl_close($ch);
  if (empty($output)) { var_dump($output); exit; }
  $result = json_decode($output);
  $token = $result->access_token;
   
  //创建菜单
  $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$token";
  $jsonData = file_get_contents("menu.json");
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
  curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER[&#39;HTTP_USER_AGENT&#39;]);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  $output = curl_exec($ch);
  curl_close($ch); 
  var_dump($output);
 ?>
 </body>
</html>
登入後複製

menu.json 

{
 "button":[
  {"type":"click","name":"我的信息","sub_button":[
   {"type":"click","name":"拇指查询","key":"BUTTON_1"},
  {"type":"click","name":"拇指请假","key":"BUTTON_2"},
  {"type":"view","name":"工号绑定","url":"http://XXXXXXXXXXXXXXXXX"}]
 },
  {"type":"click","name":"业务流程","key":"BUTTON_3"},
  {"name":"员工建议","sub_button":[
   {"type":"view","name":"思想火花","url":"http://XXXXXXXXXXXXXXXXXX"},
   {"type":"view","name":"奖品兑换","url":"http://XXXXXXXXXXXXXXXXXX"},
   {"type":"click","name":"赞一下我们","key":"BUTTON_ZAN"}]
  }
 ]
}
登入後複製

 回應自訂選單事件

 $wechatObj = new wechatCallbackAPI();
 if (isset($_GET["echostr"])) { 
  $wechatObj->valid(); 
 } else { 
  $wechatObj->responseMsg();
 }


 class wechatCallbackAPI {

  private $token = "WEIXIN";

  private $appId = "APPID";

  private $appSecret = "APPSECRET";
  
  private function checkSignature() {
   $signature = $_GET["signature"];
   $timestamp = $_GET["timestamp"];
   $nonce = $_GET["nonce"]; 
     
   $tmpArr = array($this->token, $timestamp, $nonce);
   sort($tmpArr);
   $tmpStr = implode($tmpArr);
   $tmpStr = sha1($tmpStr);
   
   if($tmpStr == $signature) {
    return true;
   } else {
    return false;
   }
  }

  private function getAccessToken() {
   $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";

   $ch = curl_init($url);
   $curl_setopt($ch, CURLOPT_HEADER, 0);
   $curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   $curl_setopt($ch, CURLOPT_POST, 0);
   $curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
   $curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

   $output = curl_exec($ch);
   curl_close($ch);
   if (empty($output)) { return ""; }

   $result = json_decode($result);
   return $result->access_token;
  }

  public function valid() {
   $echoStr = $_GET["echostr"];
   
   //valid signature, option
   if($this->checkSignature()){
    echo $echoStr;
    exit;
   }
  }
 
  public function responseMsg() {
   //get post data, May be due to the different environments
   $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
   if (empty($postStr)){
    echo "";
    exit;
   }

   //extract post data
   $postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
   $fromUsername = $postObj->FromUserName;
   $toUsername = $postObj->ToUserName;
   $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>";
   
   switch (strtolower(trim($postObj->MsgType))) {
    case "text": //文本消息
     $keyword = trim($postObj->Content);
     if(!empty($keyword)) {
      $msgType = "text";
      $contentStr = "$fromUsername, 您发送了文本信息: $keyword ";
      if (strtolower($keyword) == "time") {
       $contentStr = date("Y-m-d H:i:s", $time);
      }
      $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
     } else {
      $resultStr = "Input something...";
     }
     break;
    case "image": //图片消息
     $msgType = "text";
     $contentStr = "$fromUsername, 您发送了图片信息";
     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
     break;
    case "voice": //声音消息
     $msgType = "text";
     $contentStr = "$fromUsername, 您发送了声音信息";
     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
     break;
    case "video": //视频消息
     $msgType = "text";
     $contentStr = "$fromUsername, 您发送了视频信息";
     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
     break;
    case "location": //位置消息
     $msgType = "text";
     $contentStr = "$fromUsername, 您发送了位置信息";
     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
     break;
    case "link": //链接消息
     $msgType = "text";
     $contentStr = "$fromUsername, 您发送了链接信息";
     $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
     break;
    case "event": //事件
     switch (strtolower(trim($postObj->Event))) {
      case "subscribe": //关注事件
       $msgType = "text";
       $contentStr = "欢迎您关注XXXXXXX";
       $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
       break;
      case "unsubscribe": //取消关注事件
       break;
      case "scan": //用户已关注时扫描二维码事件
       $msgType = "text";
       $contentStr = "$fromUsername, 您扫描了二维码";
       $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
       break;
      case "location": //上传地理位置事件
       $msgType = "text";
       $contentStr = "$fromUsername, 您上传地理位置";
       $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
       break;
      case "click": //自定义菜单事件
       $msgType = "text";
       $contentStr = "$fromUsername, 您点击了自定义菜单 $postObj->EventKey ";
       if ("BUTTON_ZAN" == $postObj->EventKey) {
        $contentStr = "感谢您的赞,我们会继续提供更优质的服务。";
       }
       $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
       ;
       break;
      default:
       $resultStr = "";
     }
     break;
    default:
     $resultStr = "";
   }
   echo $resultStr;
  }
 }
?>
登入後複製

自訂選單查詢 

#使用介面建立自訂選單後,開發者也可使用介面查詢自訂選單的結構。

請求說明
 http請求方式:GET
https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN

 回傳說明
 對應創建接口,正確的Json返回結果:

複製程式碼 程式碼如下:

{"menu":{"button":[{"name":"我的信息","sub_button":[ {"type":"click","name":"拇指查詢","key":"BUTTON_1","sub_button":[]},{"type":"click","name":"拇指請假","key":"BUTTON_2","sub_button":[]},{"type":"view","name":"工號綁定","url":"http:\/\/XXXXXXXX ","sub_button":[]}]},{"type":"click","name":"業務流程","key":"BUTTON_3","sub_button":[]},{"name" :"員工建議","sub_button":[{"type":"view","name":"思想火花","url":"http:\/\/XXXXXXXX","sub_button":[]} ,{"type":"view","name":"獎品兌換","url":"http:\/\/XXXXXXXX","sub_button":[]},{"type":"click", "name":"讚一下我們","key":"BUTTON_ZAN","sub_button":[]}]}]}}

自訂選單刪除 

使用介面建立自訂選單後,開發者也會使用介面刪除目前使用的自訂選單。

請求說明
http請求方式:GET
#https://api.weixin.qq.com/cgi-bin/menu/delete ?access_token=ACCESS_TOKEN

返回說明
 對應建立接口,正確的Json返回結果:
{"errcode":0,"errmsg" :"ok"}

總結:以上就是這篇文章的全部內容,希望能對大家的學習有所幫助。

相關推薦:

PHP陣列相加運算與與array_merge的差異

PHP中call_user_func_array回呼函數的用法

#

PHP使用curl函數傳送Post請求的注意事項

以上是php微信開發自訂選單的方法分享的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!