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

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

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

<?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="<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
//            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 = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>2</ArticleCount><Articles>";
                $item = sprintf($template,$objparam->FromUserName,$objparam->ToUserName,time());
                foreach ($paramArr as $key => $v) {
                    $item.="<item><Title><![CDATA[".$v['title']."]]></Title><Description><![CDATA[".$v['desc']."]]></Description><PicUrl><![CDATA[".$v['picurl']."]]></PicUrl><Url><![CDATA[".$v['url']."]]></Url></item>";
                }
                $item.="</Articles></xml>";
                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 = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
        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 "<img src='".$getCodeUrl."'/>";
    }

}

?>











//adcance


<?php
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="<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
//        error_log(1);
//        按钮事件
        if($objparam->MsgType=='event'&&$objparam->Event=='CLICK'){
//            error_log(2);
            if($objparam->EventKey=="jin"){
                $text ="请输入房间号:
 更多好玩游戏等你翻牌,<a href=\"https://lnk0.com/swtUV1\"> 戳这里>> </a>";

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

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


    }
//    回复文本
    public function  subscribe($objparam,$text){
        $tousername = $objparam->FromUserName;
        $fromusername = $objparam->ToUserName;
        $time = time();
        $template = "<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[%s]]></Content></xml>";
        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 "<img src='".$getCodeUrl."'/>";
    }

}

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值