yii框架开发微信公众号 回复内容

使用yii 框架开发微信公众号 包括文字回复  图文回复 自定义菜单

在controller控制器中 WxController.php 代码如下

/*

*content  微信公众号回复内容

*author zhanghuan

*time  2018年2月19日19:44:44

*/

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

class WxController extends Controller
{
    public $request;
    public  function init(){
        parent::init();
        $this->request=yii::$app->request;

    }

//微信平台接入  首先进行这一步  其中有一个echostr 先进行微信平台接入

    public function sign(){
        $signature = $this->request->get('signature');
        $timestamp = $this->request->get('timestamp');
        $nonce     = $this->request->get('nonce');
        $token     = 'weixin';
        $tmpArr    = array($token,$timestamp,$nonce);
        sort($tmpArr);
        $tmpStr    = implode($tmpArr);
        $tmpStr    = sha1($tmpStr);
        if ($tmpStr == $signature) {
            return true;
        }
        else{
            return false;
        }
    }
    public  function actionIndex(){
        $echostr   = $this->request->get('echostr','');
        if ($this->sign()) {
            if ($echostr) {
                return $echostr;
            }
            else{
                return  $this->responseMes();
            }
        }

    }
    public function responseMes(){
        //接受微信服务器推送过来的数据包
        $xmlParam = $GLOBALS['HTTP_RAW_POST_DATA'];
        //将xml格式的数据转化为对象
        $objparam = simplexml_load_string($xmlParam);
        //消息回复
//        if(strtolower($objparam->MsgType)=='text'){
//            $content = "您输入的是".$objparam->Content;
//            $tousername=$objparam->FromUserName;
//            $fromusername=$objparam->ToUserName;
//            $time=time();
//            $template="%s";
//            return sprintf($template,$tousername,$fromusername,$time,$content);
//        }
        //回复图文
        if(strtolower($objparam->MsgType)=='text'){
            $tousername=$objparam->FromUserName;
            $fromusername=$objparam->ToUserName;
            $time=time();
            if($objparam->Content == '百度'){
                $paramArr[0] = array('title'=>'百度','desc'=>'百度一下','picurl'=>'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1526441472939&di=3d5f9dcb94c98f7e2b234771f4ad509b&imgtype=0&src=http%3A%2F%2Fimage.tibet.cn%2Fimages%2F2016%2F7%2F2%2F2016721467426045432_66.jpg','url'=>'http://www.baidu.com');
                $paramArr[1] = array('title'=>'百度啥是啥','desc'=>'百度一下是什么意思呀','picurl'=>'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1526441472939&di=3d5f9dcb94c98f7e2b234771f4ad509b&imgtype=0&src=http%3A%2F%2Fimage.tibet.cn%2Fimages%2F2016%2F7%2F2%2F2016721467426045432_66.jpg','url'=>'https://zhidao.baidu.com/question/750419188007494012.html');
                $template = "%s2";
                $item = sprintf($template,$objparam->FromUserName,$objparam->ToUserName,time());
                foreach ($paramArr as $key => $v) {
                    $item.="<![CDATA[".$v['title']."]]>";
                }
                $item.="
";
                return $item;
            }

        }
        //事件推送
        if ($objparam->MsgType=='event'&&$objparam->Event='subscribe'){
            return  $this->subscribe($objparam);
        }
    }
    public function  subscribe($objparam){
        $tousername = $objparam->FromUserName;
        $fromusername = $objparam->ToUserName;
        $time = time();
        $text = "欢迎关注本仙女!";
        $template = "%s";
        return  sprintf($template,$tousername,$fromusername,$time,$text);

    }
    public function GetAccessToken(){
        $cache = yii::$app->cache;
        if($access_token=$cache->get('access_token')){
            return $access_token;
        }else{
            $appid = "wx5ea6f7917056fdb1";
            $appsecret = "da3a0202560da91de4b9e1a317afd9dc";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
            $result=$this->http_curl($url);
            $cache->set('access_token',$result['access_token'],$result['expires_in']);
            return $result['access_token'];
        }
    }
    public function http_curl($url,$type='get',$postdata=''){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        if ($type=='post'){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$postdata);
        }
        $result = curl_exec($ch);
        if (curl_errno($ch)){
            return false;
            curl_close($ch);
        }else{
            return json_decode($result,true);
        }
    }

//    public function http_curl($url,$type='get',$postData=''){
//        //初始化句柄
//        $ch = curl_init();
//        //设置
//        curl_setopt($ch,CURLOPT_URL,$url);
//        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//        if($type="post"){
//            curl_setopt($ch,CURLOPT_POST,1);
//            CURL_SETOPT($ch,CURLOPT_POSTFIELDS,$postData);
//        }
//        //执行
//        $result=curl_exec($ch);
//        if(curl_errno($ch)){
//            return false;
//            curl_close($ch);
//        }else{
//            return json_decode($result,true);
//        }
//
//    }
 public function actionDefinedMenu(){
        header("content-type:text/html;charset=utf-8");
        $access_token=$this->getAccessToken();
        $url = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$access_token";
        $postData['button'] = [
            ['name'=>'常用命令','sub_button'=>[ ['type'=>'click','name'=>'进','key'=>'jin;'],
                ['type'=>'click','name'=>'领','key'=>'ling'],
                ['type'=>'click','name'=>'换','key'=>'huan'],
                ['type'=>'click','name'=>'开','key'=>'kai'],
                ['type'=>'click','name'=>'罚','key'=>'fa']]
            ],
            ['name'=>'谁是卧底','sub_button'=>[['type'=>'click','name'=>'谁是卧底小程序','key'=>'wodi'],
                ['type'=>'click','name'=>'谁是卧底怎么玩','key'=>'wan']]
            ],
            ['name'=>'游戏合集','sub_button'=>[['type'=>'click','name'=>'你画我猜','key'=>'cai'],
                ['type'=>'click','name'=>'狼人杀','key'=>'sha'],['type'=>'click','name'=>'更多好玩小游戏','key'=>'game']]
            ]
        ];
        $postData=urldecode(json_encode($postData));
        var_dump($postData);die;
        $result=$this->http_curl($url,$postData);
//        var_dump($result);


    }
    public function actionCreateQrscene(){
        $access_token=$this->getAccessToken();
        $url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$access_token";
        $postData=["expire_seconds"=> 604800, "action_name"=> "QR_SCENE", "action_info"=> ["scene"=> ["scene_str"=> 123]]];
        $jsonData=json_encode($postData);
        $result=$this->http_curl($url,'post',$jsonData);
        $getCodeUrl="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($result['ticket']);
        echo "";
    }

}

?>











//adcance


namespace backend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;

class WxController extends Controller
{
    public $request;
    public  function init(){
        parent::init();
        $this->request=yii::$app->request;

    }
//    微信平台接入
    public function sign(){
        $signature = $this->request->get('signature');
        $timestamp = $this->request->get('timestamp');
        $nonce     = $this->request->get('nonce');
        $token     = 'weixin';
        $tmpArr    = array($token,$timestamp,$nonce);
        sort($tmpArr);
        $tmpStr    = implode($tmpArr);
        $tmpStr    = sha1($tmpStr);
        if ($tmpStr == $signature) {
            return true;
        }
        else{
            return false;
        }
    }
//    默认访问
    public  function actionIndex(){
        $echostr   = $this->request->get('echostr','');
        if ($this->sign()) {
            if ($echostr) {
                return $echostr;
            }
            else{
                return  $this->responseMes();
            }
        }

    }
//    判断是什么事件,
    public function responseMes(){
        //接受微信服务器推送过来的数据包
        $xmlParam = $GLOBALS['HTTP_RAW_POST_DATA'];
        //将xml格式的数据转化为对象
        $objparam = simplexml_load_string($xmlParam);
        //消息回复
//        if(strtolower($objparam->MsgType)=='text'){
//            $content = "您输入的是".$objparam->Content;
//            $tousername=$objparam->FromUserName;
//            $fromusername=$objparam->ToUserName;
//            $time=time();
//            $template="%s";
//        error_log(1);
//        按钮事件
        if($objparam->MsgType=='event'&&$objparam->Event=='CLICK'){
//            error_log(2);
            if($objparam->EventKey=="jin"){
                $text ="请输入房间号:
 更多好玩游戏等你翻牌, 戳这里>> ";

                return  $this->subscribe($objparam,$text);

            }else if($objparam->EventKey=="ling"){
                $ling = "请先进入房间,之后才能使用此命令!
 更多好玩游戏等你翻牌,戳这里>>";
                return $this->subscribe($objparam,$ling);
            }else if($objparam->EventKey=="huan"){
                $huan="房间:
平民词: 道歉
卧底词: 抱歉
题目已改,请让其他玩家对我输入'领'来领新词。
所有玩家的身份也已重新分配:你是法官;号玩家是卧底。
输【罚】看看大冒险惩罚吧
 更多好玩游戏等你翻牌,戳这里>>";
                return $this->subscribe($objparam,$huan);
            }else if($objparam->EventKey=="kai"){
                $kai="一共几个人玩?
(请直接回复数字,如“6”。
记得要算上你自己哦,我的法官大人)
 更多好玩游戏等你翻牌,戳这里>>";
                return $this->subscribe($objparam,$kai);
            }else if($objparam->EventKey=="fa"){
                $fa="请先进入房间,之后才能使用此命令!
 更多好玩游戏等你翻牌,戳这里>>";
                return $this->subscribe($objparam,$fa);
            }
        }
        //关注事件推送
        if ($objparam->MsgType=='event'&&$objparam->Event=='subscribe'){
            $text = "Hi~(????)??恭喜你找到了最贴心的聚会神器——谁是卧底助手。
 快速开局点击菜单栏【常用命令】
 第一次玩谁是卧底?回复【帮】就能快速上手啦~
 凑不齐人开不了局?超多好玩小游戏线上嗨起来!立刻开局>>";
            return  $this->subscribe($objparam,$text);
        }


    }
//    回复文本
    public function  subscribe($objparam,$text){
        $tousername = $objparam->FromUserName;
        $fromusername = $objparam->ToUserName;
        $time = time();
        $template = "%s";
        return  sprintf($template,$tousername,$fromusername,$time,$text);

    }
//    获取token
    public function GetAccessToken(){
        $cache = yii::$app->cache;
        if($access_token=$cache->get('access_token')){
            return $access_token;
        }else{
            $appid = "wx5ea6f7917056fdb1";
            $appsecret = "da3a0202560da91de4b9e1a317afd9dc";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
            $result=$this->http_curl($url);
            $cache->set('access_token',$result['access_token'],$result['expires_in']);
            return $result['access_token'];
        }
    }
//    菜单生成
    public function http_curl($url,$type='get',$postdata=''){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        if ($type=='post'){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$postdata);
        }
        $result = curl_exec($ch);
        if (curl_errno($ch)){
            return false;
            curl_close($ch);
        }else{
            return json_decode($result,true);
        }
    }
//    菜单
    public function actionDefinedMenu(){
        header("content-type:text/html;charset=utf-8");
        $access_token=$this->getAccessToken();
        $url = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token=$access_token";
        $postData['button'] = [
            ['name'=>'常用命令','sub_button'=>[ ['type'=>'click','name'=>'进','key'=>'jin'],
                ['type'=>'click','name'=>'领','key'=>'ling'],
                ['type'=>'click','name'=>'换','key'=>'huan'],
                ['type'=>'click','name'=>'开','key'=>'kai'],
                ['type'=>'click','name'=>'罚','key'=>'fa']]
            ],
            ['name'=>'谁是卧底','sub_button'=>[['type'=>'click','name'=>'谁是卧底小程序','key'=>'who'],
                ['type'=>'click','name'=>'谁是卧底怎么玩','key'=>'wan']]
            ],
            ['name'=>'游戏合集','sub_button'=>[['type'=>'click','name'=>'你画我猜','key'=>'guss'],
                ['type'=>'click','name'=>'狼人杀','key'=>'sha'],['type'=>'click','name'=>'更多好玩小游戏','key'=>'game']]
            ]
        ];
        $postData=urldecode(json_encode($postData));
        echo $this->GetAccessToken();die;
        print_r($postData);die;
        $result=$this->http_curl($url,$postData);
//        var_dump($result);


    }
//    图文回复
    public function actionCreateQrscene(){
        $access_token=$this->getAccessToken();
        $url="https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=$access_token";
        $postData=["expire_seconds"=> 604800, "action_name"=> "QR_SCENE", "action_info"=> ["scene"=> ["scene_str"=> 123]]];
        $jsonData=json_encode($postData);
        $result=$this->http_curl($url,'post',$jsonData);
        $getCodeUrl="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($result['ticket']);
        echo "";
    }

}

?>

你可能感兴趣的:(yii框架开发微信公众号 回复内容)