php微信开发自定义菜单


Posted in PHP onAugust 27, 2016

目前微信服务号自定义菜单最多包括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"}]
  }
 ]
}

参数说明

php微信开发自定义菜单

返回结果 
正确时的返回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['HTTP_USER_AGENT']);
  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, 'SimpleXMLElement', 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 相关文章推荐
PHP+MYSQL 出现乱码的解决方法
Aug 08 PHP
php提交表单时判断 if($_POST[submit])与 if(isset($_POST[submit])) 的区别
Feb 08 PHP
PHP第一季视频教程(李炎恢+php100 不断更新)
May 29 PHP
PHP+Mysql+jQuery实现动态展示信息
Oct 08 PHP
php使用多个进程同时控制文件读写示例
Feb 28 PHP
采用memcache在web集群中实现session的同步会话
Jul 05 PHP
wordpress安装过程中遇到中文乱码的处理方法
Apr 21 PHP
php格式化电话号码的方法
Apr 24 PHP
php导出中文内容excel文件类实例
Jul 06 PHP
php mysqli查询语句返回值类型实例分析
Jun 29 PHP
Yii2.0中使用js异步删除示例
Mar 10 PHP
PHP实现长轮询消息实时推送功能代码实例讲解
Feb 26 PHP
PHP7新特性foreach 修改示例介绍
Aug 26 #PHP
简单的自定义php模板引擎
Aug 26 #PHP
PHP flush 函数使用注意事项
Aug 26 #PHP
PHP获取不了React Native Fecth参数的解决办法
Aug 26 #PHP
简单的pgsql pdo php操作类实现代码
Aug 25 #PHP
php mongodb操作类 带几个简单的例子
Aug 25 #PHP
php flush无效,IIS7下php实时输出的方法
Aug 25 #PHP
You might like
ThinkPHP实现将本地文件打包成zip下载
2014/06/26 PHP
项目中应用Redis+Php的场景
2016/05/22 PHP
PHP 实现页面静态化的几种方法
2017/07/23 PHP
Windows服务器中PHP如何安装redis扩展
2019/09/27 PHP
基于JQuery 选择器使用说明介绍
2013/04/18 Javascript
Js放到HTML文件中的哪个位置有什么区别
2013/08/21 Javascript
javascript实现左右控制无缝滚动
2014/12/31 Javascript
Jquery中request和request.form和request.querystring的区别
2015/11/26 Javascript
Js的Array数组对象详解
2016/02/22 Javascript
Dojo获取下拉框的文本和值实例代码
2016/05/27 Javascript
原生js实现选项卡功能
2017/03/08 Javascript
Vue resource三种请求格式和万能测试地址
2018/09/26 Javascript
vue实现新闻展示页的步骤详解
2019/04/11 Javascript
es6数组的flat(),flatMap()函数用法实例分析
2020/04/18 Javascript
简单了解three.js 着色器材质
2020/08/03 Javascript
JavaScript实现通讯录功能
2020/12/27 Javascript
[01:02:18]VGJ.S vs infamous Supermajor 败者组 BO3 第一场 6.4
2018/06/05 DOTA
[03:00]DOTA2-DPC中国联赛1月18日Recap集锦
2021/03/11 DOTA
浅析Python中yield关键词的作用与用法
2016/11/29 Python
删除DataFrame中值全为NaN或者包含有NaN的列或行方法
2018/11/06 Python
python使用response.read()接收json数据的实例
2018/12/19 Python
Python判断两个文件是否相同与两个文本进行相同项筛选的方法
2019/03/01 Python
pyqt5与matplotlib的完美结合实例
2019/06/21 Python
关于Python核心框架tornado的异步协程的2种方法详解
2019/08/28 Python
Pytorch基本变量类型FloatTensor与Variable用法
2020/01/08 Python
Python数据可视化实现多种图例代码详解
2020/07/14 Python
Python 制作查询商品历史价格的小工具
2020/10/20 Python
BNKR中国官网:带你感受澳洲领先潮流时尚
2018/08/21 全球购物
Swanson中国官网:美国斯旺森健康产品公司
2021/03/01 全球购物
求职信名称怎么写
2014/05/26 职场文书
感谢信格式范文
2015/01/22 职场文书
债务纠纷代理词
2015/05/25 职场文书
公司晚会主持词
2019/04/17 职场文书
CSS3 制作的书本翻页特效
2021/04/13 HTML / CSS
Python基础之数据结构详解
2021/04/28 Python
如何理解Vue前后端数据交互与显示
2021/05/10 Vue.js