Home php教程 php手册 php版微信公众平台账号自定义菜单类

php版微信公众平台账号自定义菜单类

Jun 02, 2016 am 09:14 AM
foreach

微信公众平台服务号可申请自定义菜单了,其它的号暂时不支持自定义菜单了,这个不但可以使用api来操作,还可以直接在后台定义菜单与参数哦。

申请自定义菜单

服务号可以申请自定义菜单;使用QQ登录的公众号,可以升级为邮箱登录;使用邮箱登录的公众号,可以修改登录邮箱;群发消息可以同步到腾讯微博。

微信公众平台升级:服务号可申请自定义菜单

微信公众平台账号api程序

<?php
//define your token
define("TOKEN", "chenxiang"); //改成自己的TOKEN
define(&#39;APP_ID&#39;, &#39;&#39;); //改成自己的APPID
define(&#39;APP_SECRET&#39;, &#39;&#39;); //改成自己的APPSECRET
$wechatObj = new wechatCallbackapiTest(APP_ID, APP_SECRET);
$wechatObj->Run();
class wechatCallbackapiTest {
    private $fromUsername;
    private $toUsername;
    private $times;
    private $keyword;
    private $app_id;
    private $app_secret;
    public function __construct($appid, $appsecret) {
        // code...
        $this->app_id = $appid;
        $this->app_secret = $appsecret;
    }
    public function valid() {
        $echoStr = $_GET["echostr"];
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }
    /**
     * 运行程序
     * @param string $value [description]
     */
    public function Run() {
        $this->responseMsg();
        $arr[] = "您好,这是自动回复,我现在不在,有事请留言,我会尽快回复你的^_^";
        echo $this->make_xml("text", $arr);
    }
    public function responseMsg() {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //返回回复数据
        if (!empty($postStr)) {
            $access_token = $this->get_access_token(); //获取access_token
            $this->createmenu($access_token); //创建菜单
            //$this->delmenu($access_token);//删除菜单
            $postObj = simplexml_load_string($postStr, &#39;SimpleXMLElement&#39;, LIBXML_NOCDATA);
            $this->fromUsername = $postObj->FromUserName; //发送消息方ID
            $this->toUsername = $postObj->ToUserName; //接收消息方ID
            $this->keyword = trim($postObj->Content); //用户发送的消息
            $this->times = time(); //发送时间
            $MsgType = $postObj->MsgType; //消息类型
            if ($MsgType == &#39;event&#39;) {
                $MsgEvent = $postObj->Event; //获取事件类型
                if ($MsgEvent == &#39;subscribe&#39;) { //订阅事件
                    $arr[] = "你好,我是xxx,现在我们是好友咯![愉快][玫瑰]";
                    echo $this->make_xml("text", $arr);
                    exit;
                } elseif ($MsgEvent == &#39;CLICK&#39;) { //点击事件
                    $EventKey = $postObj->EventKey; //菜单的自定义的key值,可以根据此值判断用户点击了什么内容,从而推送不同信息
                    $arr[] = $EventKey;
                    echo $this->make_xml("text", $arr);
                    exit;
                }
            }
        } else {
            echo "this a file for weixin API!";
            exit;
        }
    }
    /**
     * 获取access_token
     */
    private function get_access_token() {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->app_id . "&secret=" . $this->app_secret;
        $data = json_decode(file_get_contents($url) , true);
        if ($data[&#39;access_token&#39;]) {
            return $data[&#39;access_token&#39;];
        } else {
            return "获取access_token错误";
        }
    }
    /**
     * 创建菜单
     * @param $access_token 已获取的ACCESS_TOKEN
     */
    public function createmenu($access_token) {
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $access_token;
        $arr = array(
            &#39;button&#39; => array(
                array(
                    &#39;name&#39; => urlencode("生活查询") ,
                    &#39;sub_button&#39; => array(
                        array(
                            &#39;name&#39; => urlencode("天气查询") ,
                            &#39;type&#39; => &#39;click&#39;,
                            &#39;key&#39; => &#39;VCX_WEATHER&#39;
                        ) ,
                        array(
                            &#39;name&#39; => urlencode("身份证查询") ,
                            &#39;type&#39; => &#39;click&#39;,
                            &#39;key&#39; => &#39;VCX_IDENT&#39;
                        )
                    )
                ) ,
                array(
                    &#39;name&#39; => urlencode("轻松娱乐") ,
                    &#39;sub_button&#39; => array(
                        array(
                            &#39;name&#39; => urlencode("刮刮乐") ,
                            &#39;type&#39; => &#39;click&#39;,
                            &#39;key&#39; => &#39;VCX_GUAHAPPY&#39;
                        ) ,
                        array(
                            &#39;name&#39; => urlencode("幸运大转盘") ,
                            &#39;type&#39; => &#39;click&#39;,
                            &#39;key&#39; => &#39;VCX_LUCKPAN&#39;
                        )
                    )
                ) ,
                array(
                    &#39;name&#39; => urlencode("我的信息") ,
                    &#39;sub_button&#39; => array(
                        array(
                            &#39;name&#39; => urlencode("关于我") ,
                            &#39;type&#39; => &#39;click&#39;,
                            &#39;key&#39; => &#39;VCX_ABOUTME&#39;
                        ) ,
                        array(
                            &#39;name&#39; => urlencode("工作信息") ,
                            &#39;type&#39; => &#39;click&#39;,
                            &#39;key&#39; => &#39;VCX_JOBINFORMATION&#39;
                        )
                    )
                )
            )
        );
        $jsondata = urldecode(json_encode($arr));
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsondata);
        curl_exec($ch);
        curl_close($ch);
    }
    /**
     * 查询菜单
     * @param $access_token 已获取的ACCESS_TOKEN
     */
    private function getmenu($access_token) {
        // code...
        $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" . $access_token;
        $data = file_get_contents($url);
        return $data;
    }
    /**
     * 删除菜单
     * @param $access_token 已获取的ACCESS_TOKEN
     */
    private function delmenu($access_token) {
        // code...
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" . $access_token;
        $data = json_decode(file_get_contents($url) , true);
        if ($data[&#39;errcode&#39;] == 0) {
            // code...
            return true;
        } else {
            return false;
        }
    }
    /**
     *@param type: text 文本类型, news 图文类型
     *@param value_arr array(内容),array(ID)
     *@param o_arr array(array(标题,介绍,图片,超链接),...小于10条),array(条数,ID)
     */
    private function make_xml($type, $value_arr, $o_arr = array(
        0
    )) {
        //=================xml header============
        $con = "<xml>
                    <ToUserName><![CDATA[{$this->fromUsername}]]></ToUserName>
                    <FromUserName><![CDATA[{$this->toUsername}]]></FromUserName>
                    <CreateTime>{$this->times}</CreateTime>
                    <MsgType><![CDATA[{$type}]]></MsgType>";
        //=================type content============
        switch ($type) {
            case "text":
                $con.= "<Content><![CDATA[{$value_arr[0]}]]></Content>
                    <FuncFlag>{$o_arr}</FuncFlag>";
                break;

            case "news":
                $con.= "<ArticleCount>{$o_arr[0]}</ArticleCount>
                     <Articles>";
                foreach ($value_arr as $id => $v) {
                    if ($id >= $o_arr[0]) break;
                    else null; //判断数组数不超过设置数
                    $con.= "<item>
                         <Title><![CDATA[{$v[0]}]]></Title> 
                         <Description><![CDATA[{$v[1]}]]></Description>
                         <PicUrl><![CDATA[{$v[2]}]]></PicUrl>
                         <Url><![CDATA[{$v[3]}]]></Url>
                         </item>";
                }
                $con.= "</Articles>
                     <FuncFlag>{$o_arr[1]}</FuncFlag>";
                break;
            } //end switch
            //=================end return============
            $con.= "</xml>";
            return $con;
        }
        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;
            }
        }
}
?>
Copy after login


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

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

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)

What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? Apr 27, 2023 pm 03:40 PM

1. The difference between Iterator and foreach is the polymorphic difference (the bottom layer of foreach is Iterator) Iterator is an interface type, it does not care about the type of collection or array; both for and foreach need to know the type of collection first, even the type of elements in the collection; 1. Why is it said that the bottom layer of foreach is the code written by Iterator: Decompiled code: 2. The difference between remove in foreach and iterator. First, look at the Alibaba Java Development Manual, but no error will be reported in case 1, and an error will be reported in case 2 (java. util.ConcurrentModificationException) first

How to determine the number of foreach loop in php How to determine the number of foreach loop in php Jul 10, 2023 pm 02:18 PM

​The steps for PHP to determine the number of the foreach loop: 1. Create an array of "$fruits"; 2. Create a counter variable "$counter" with an initial value of 0; 3. Use "foreach" to loop through the array, and Increase the value of the counter variable in the loop body, and then output each element and their index; 4. Output the value of the counter variable outside the "foreach" loop to confirm which element the loop reaches.

PHP returns an array with key values ​​flipped PHP returns an array with key values ​​flipped Mar 21, 2024 pm 02:10 PM

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values ​​in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values ​​swapped. $original_array=[

PHP returns the current element in an array PHP returns the current element in an array Mar 21, 2024 pm 12:36 PM

This article will explain in detail about the current element in the array returned by PHP. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. Get the current element in a PHP array PHP provides a variety of methods for accessing and manipulating arrays, including getting the current element in an array. The following introduces several commonly used techniques: 1. current() function The current() function returns the element currently pointed to by the internal pointer of the array. The pointer initially points to the first element of the array. Use the following syntax: $currentElement=current($array);2.key() function key() function returns the array internal pointer currently pointing to the element

What is the difference between foreach and for loop What is the difference between foreach and for loop Jan 05, 2023 pm 04:26 PM

Difference: 1. for loops through each data element through the index, while forEach loops through the data elements of the array through the JS underlying program; 2. for can terminate the execution of the loop through the break keyword, but forEach cannot; 3. for can control the execution of the loop by controlling the value of the loop variable, but forEach cannot; 4. for can call loop variables outside the loop, but forEach cannot call loop variables outside the loop; 5. The execution efficiency of for is higher than forEach.

How to iterate through the properties of an object using the forEach function? How to iterate through the properties of an object using the forEach function? Nov 18, 2023 pm 06:10 PM

How to iterate through the properties of an object using the forEach function? In JavaScript, we often need to traverse the properties of objects. If you want to use a concise way to iterate over the properties of an object, the forEach function is a very good choice. In this article, we will explain how to use the forEach function to iterate over the properties of an object and provide specific code examples. First, let's understand the basic usage of the forEach function. forEach function is Java

Advanced skills of Java Map: Master cold knowledge you may not know and improve your programming skills Advanced skills of Java Map: Master cold knowledge you may not know and improve your programming skills Feb 19, 2024 pm 12:33 PM

Map interface overview The Map interface is a data structure used to store key-value pairs in the Java collection framework. It allows you to use keys to find and retrieve associated values. The Map interface provides many useful methods, including put(), get(), remove(), containsKey(), containsValue(), size(), isEmpty(), etc. Implementation of Map The most commonly used Map implementations in Java are HashMap and TreeMap. HashMap is a hash table-based Map implementation that quickly finds and retrieves values ​​by calculating the hash value of the key. TreeMap is a Map implementation based on red-black trees, which sorts keys in ascending or descending order.

How to get the index value of the current element in php foreach loop How to get the index value of the current element in php foreach loop Mar 23, 2023 am 09:17 AM

In PHP, the foreach statement is widely used to traverse arrays and objects. During the loop, we sometimes need to get the current element of the loop. This article will introduce how to get the index value of the current element in the PHP foreach loop.

See all articles