快捷搜索:

微信公众平台开发通过php创建自定义菜单,php实现发送微信模板消息的方法

2019-11-16 15:32栏目:计算机网络
TAG:

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

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

验证配置

本文实例讲述了php实现发送微信模板消息的方法。分享给大家供大家参考。具体如下:

申请自定义菜单

 代码如下

 代码如下

<?php
namespace OrgWeixin;
/**
 * Created by PhpStorm.
 * User: StandOpen
 * Date: 15-1-7
 * Time: 9:41
 */
class OrderPush
{
    protected $appid;
    protected $secrect;
    protected $accessToken;
    function  __construct($appid, $secrect)
    {
        $this->appid = $appid;
        $this->secrect = $secrect;
        $this->accessToken = $this->getToken($appid, $secrect);
    }
    /**
     * 发送post请求
     * @param string $url
     * @param string $param
     * @return bool|mixed
     */
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return $data;
    }
    /**
     * 发送get请求
     * @param string $url
     * @return bool|mixed
     */
    function request_get($url = '')
    {
        if (empty($url)) {
            return false;
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    /**
     * @param $appid
     * @param $appsecret
     * @return mixed
     * 获取token
     */
    protected function getToken($appid, $appsecret)
    {
        if (S($appid)) {
            $access_token = S($appid);
        } else {
            $url = "" . $appid . "&secret=" . $appsecret;
            $token = $this->request_get($url);
            $token = json_decode(stripslashes($token));
            $arr = json_decode(json_encode($token), true);
            $access_token = $arr['access_token'];
            S($appid, $access_token, 720);
        }
        return $access_token;
    }
    /**
     * 发送自定义的模板消息
     * @param $touser
     * @param $template_id
     * @param $url
     * @param $data
     * @param string $topcolor
     * @return bool
     */
    public function doSend($touser, $template_id, $url, $data, $topcolor = '#7B68EE')
    {
        /*
         * data=>array(
                'first'=>array('value'=>urlencode("您好,您已购买成功"),'color'=>"#743A3A"),
                'name'=>array('value'=>urlencode("商品信息:微时代电影票"),'color'=>'#EEEEEE'),
                'remark'=>array('value'=>urlencode('永久有效!密码为:1231313'),'color'=>'#FFFFFF'),
            )
         */
        $template = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'topcolor' => $topcolor,
            'data' => $data
        );
        $json_template = json_encode($template);
        $url = "" . $this->accessToken;
        $dataRes = $this->request_post($url, urldecode($json_template));
        if ($dataRes['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

<?php
//define your token
define("TOKEN", "chenxiang");//改成自己的TOKEN
define('APP_ID', '');//改成自己的APPID
define('APP_SECRET', '');//改成自己的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 (!emptyempty($postStr)){
                $access_token = $this->get_access_token();//获取access_token
                $this->createmenu($access_token);//创建菜单
                //$this->delmenu($access_token);//删除菜单
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', 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=='event'){
                    $MsgEvent = $postObj->Event;//获取事件类型
                    if ($MsgEvent=='subscribe') {//订阅事件
                        $arr[] = "你好,我是xxx,现在我们是好友咯![愉快][玫瑰]";
                        echo $this->make_xml("text",$arr);
                        exit;
                    }elseif ($MsgEvent=='CLICK') {//点击事件
                        $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 = ";
        $data = json_decode(file_get_contents($url),true);
        if($data['access_token']){
            return $data['access_token'];
        }else{
            return "获取access_token错误";
        }
    }
    /**
     * 创建菜单
     * @param $access_token 已获取的ACCESS_TOKEN
     */
    public function createmenu($access_token)
    {
        $url = ";
        $arr = array( 
            'button' =>array(
                array(
                    'name'=>urlencode("生活查询"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("天气查询"),
                            'type'=>'click',
                            'key'=>'VCX_WEATHER'
                        ),
                        array(
                            'name'=>urlencode("身份证查询"),
                            'type'=>'click',
                            'key'=>'VCX_IDENT'
                        )
                    )
                ),
                array(
                    'name'=>urlencode("轻松娱乐"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("刮刮乐"),
                            'type'=>'click',
                            'key'=>'VCX_GUAHAPPY'
                        ),
                        array(
                            'name'=>urlencode("幸运大转盘"),
                            'type'=>'click',
                            'key'=>'VCX_LUCKPAN'
                        )
                    )
                ),
                array(
                    'name'=>urlencode("我的信息"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("关于我"),
                            'type'=>'click',
                            'key'=>'VCX_ABOUTME'
                        ),
                        array(
                            'name'=>urlencode("工作信息"),
                            'type'=>'click',
                            'key'=>'VCX_JOBINFORMATION'
                        )
                    )
                )
            )
        );
        $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 = ";
        $data = file_get_contents($url);
        return $data;
    }
    /**
     * 删除菜单
     * @param $access_token 已获取的ACCESS_TOKEN
     */
    
    private function delmenu($access_token)
    {
        # code...
        $url = ";
        $data = json_decode(file_get_contents($url),true);
        if ($data['errcode']==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;
        }
    }
}
?>

    /**
     * 创建菜单
     * @param $access_token 已获取的ACCESS_TOKEN
     */
    public function createmenu($access_token)
    {
        $url = ";
        $arr = array(
            'button' =>array(
                array(
                    'name'=>urlencode("生活查询"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("天气查询"),
                            'type'=>'click',
                            'key'=>'VCX_WEATHER'
                        ),
                        array(
                            'name'=>urlencode("身份证查询"),
                            'type'=>'click',
                            'key'=>'VCX_IDENT'
                        )
                    )
                ),
                array(
                    'name'=>urlencode("轻松娱乐"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("刮刮乐"),
                            'type'=>'click',
                            'key'=>'VCX_GUAHAPPY'
                        ),
                        array(
                            'name'=>urlencode("幸运大转盘"),
                            'type'=>'click',
                            'key'=>'VCX_LUCKPAN'
                        )
                    )
                ),
                array(
                    'name'=>urlencode("我的信息"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("关于我"),
                            'type'=>'click',
                            'key'=>'VCX_ABOUTME'
                        ),
                        array(
                            'name'=>urlencode("工作信息"),
                            'type'=>'click',
                            'key'=>'VCX_JOBINFORMATION'
                        )
                    )
                )
            )
        );
        $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);

 代码如下

该方法基于thinkphp实现实现,具体OrderPush.class.php文件如下:

复制代码 代码如下:

    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, 'SimpleXMLElement', 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=='event'){
                    $MsgEvent = $postObj->Event;//获取事件类型
                    if ($MsgEvent=='subscribe') {//订阅事件
                        $arr[] = "你好,我是xxx,现在我们是好友咯![愉快][玫瑰]";
                        echo $this->make_xml("text",$arr);
                        exit;
                    }elseif ($MsgEvent=='CLICK') {//点击事件
                        $EventKey = $postObj->EventKey;//菜单的自定义的key值,可以根据此值判断用户点击了什么内容,从而推送不同信息
                        $arr[] = $EventKey;
                        echo $this->make_xml("text",$arr);
                        exit;
                    }
                }
        }else {
            echo "this a file for weixin API!";
            exit;
        }
    }

define("TOKEN", "xxx");//改成自己的TOKEN
define('APP_ID', 'xxxx');//改成自己的APPID
define('APP_SECRET', 'xxx');//改成自己的APPSECRET

您可能感兴趣的文章:

  • php微信公众号开发模式详解
  • php 微信公众平台开发模式实现多客服的实例代码
  • PHP微信公众号自动发送红包API
  • 关于php微信订阅号开发之token验证后自动发送消息给订阅号但是没有消息返回的问题
  • PHP实现微信模拟登陆并给用户发送消息的方法【文字,图片,图文】
  • php版微信公众平台实现预约提交后发送email的方法
  • 验证token、回复图文文本、推送消息的实用微信类php代码
  • PHP memcache在微信公众平台的应用方法示例
  • PHP实现微信公众号企业号自定义菜单接口示例
  • 基于php的微信公众平台开发入门实例
  • PHP使用微信开发模式实现搜索已发送图文及匹配关键字回复的方法

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

微信公众平台账号api程序

这个类就介绍了网上多了去了,大家可以自行搜索了下,我只介绍两个创建自定义菜单的函数

希望本文所述对大家的php程序设计有所帮助。

您可能感兴趣的文章:

  • php实现微信公众平台账号自定义菜单类
  • php微信公众平台开发类实例
  • php微信公众平台开发之获取用户基本信息
  • 微信公众平台开发接口PHP SDK完整版
  • PHP实现微信公众平台音乐点播
  • php版微信公众平台之微信网页登陆授权示例
  • weiphp微信公众平台授权设置
  • php微信公众平台配置接口开发程序
  • php微信公众平台开发之微信群发信息
  • php实现基于微信公众平台开发SDK(demo)扩展的方法
  • PHP Curl模拟登录微信公众平台、新浪微博实例代码
  • PHP封装的微信公众平台接口开发操作类完整示例

    /**
     * 获取access_token
     */

使用方法是

复制代码 代码如下:

希望本文所述对大家基于PHP的微信开发有所帮助。

    }
       
    /**
     *@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;
    }

class wechatCallbackapiTest{}

微信公众平台账号api程序

 

$wechatObj = new wechatCallbackapiTest();

本文实例讲述了php实现微信公众平台账号自定义菜单类的方法。分享给大家供大家参考。具体分析如下:

    /**
     * 查询菜单
     * @param $access_token 已获取的ACCESS_TOKEN
     */
   
    private function getmenu($access_token)
    {
        # code...
        $url = ";
        $data = file_get_contents($url);
        return $data;
    }

 代码如下

    }

if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else{
    $wechatObj->responseMsg();
}

图片 1

$access_token = $wechatObj->get_access_token();//获取access_token
$wechatObj->createmenu($access_token);//创建菜单到微信公共平台

$wechatObj = new wechatCallbackapiTest(APP_ID,APP_SECRET);
$wechatObj->Run();

  /**
     * 获取access_token
     */
    public function get_access_token()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".APP_ID."&secret=".APP_SECRET;
        $data = json_decode(file_get_contents($url),true);
        if($data['access_token']){
            return $data['access_token'];
        }else{
            return "获取access_token错误";
        }
    }
 
  /**
     * 创建菜单
     * @param $access_token 已获取的ACCESS_TOKEN
     */
    public function createmenu($access_token)
    {
        $url = ";
        $arr = array( 
            'button' =>array(
                array(
                    'name'=>urlencode("aaaa"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("bbbb"),
                            'type'=>'click',
                            'key'=>'VCX_WEATHER'
                        ),
                        array(
                            'name'=>urlencode("cccc"),
                            'type'=>'click',
                            'key'=>'VCX_IDENT'
                        )
                    )
                ),
                array(
                    'name'=>urlencode("dddd"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("xxxx"),
                            'type'=>'click',
                            'key'=>'VCX_GUAHAPPY'
                        ),
                        array(
                            'name'=>urlencode("xxxx"),
                            'type'=>'click',
                            'key'=>'VCX_LUCKPAN'
                        )
                    )
                ),
                array(
                    'name'=>urlencode("xxxx"),
                    'sub_button'=>array(
                        array(
                            'name'=>urlencode("aaaa"),
                            'type'=>'click',
                            'key'=>'VCX_ABOUTME'
                        ),
                        array(
                            'name'=>urlencode("aaaaa"),
                            'type'=>'click',
                            'key'=>'VCX_JOBINFORMATION'
                        )
                    )
                )
            )
        );
        $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);
    }
 
}

<?php
//define your token
define("TOKEN", "chenxiang");//改成自己的TOKEN
define('APP_ID', '');//改成自己的APPID
define('APP_SECRET', '');//改成自己的APPSECRET

?>

 

 

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;
    }

    private function get_access_token()
    {
        $url = ";
        $data = json_decode(file_get_contents($url),true);
        if($data['access_token']){
            return $data['access_token'];
        }else{

    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;
        }
    }
}

    /**
     * 删除菜单
     * @param $access_token 已获取的ACCESS_TOKEN
     */
   
    private function delmenu($access_token)
    {
        # code...
        $url = ";
        $data = json_decode(file_get_contents($url),true);
        if ($data['errcode']==0) {
            # code...
            return true;
        }else{
            return false;
        }

    /**
     * 运行程序
     * @param string $value [description]
     */
    public function Run()
    {
        $this->responseMsg();
        $arr[]= "您好,这是自动回复,我现在不在,有事请留言,我会尽快回复你的^_^";
        echo $this->make_xml("text",$arr);
    }

            return "获取access_token错误";
        }
    }

    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

申请自定义菜单

版权声明:本文由澳门金莎娱乐发布于计算机网络,转载请注明出处:微信公众平台开发通过php创建自定义菜单,php实现发送微信模板消息的方法