• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
孙龙 程序员
少时总觉为人易,华年方知立业难
博客园    首页    新随笔    联系   管理    订阅  订阅
公共账号开发api
php 开发微信公共账号,关键词回复,事件推送 关注等

 

 

 

 

 

 

服务器地址url

    public function callbackxinychuang(){
        if(I('get.echostr')){//token验证
            echo I('get.echostr');exit();
        }
        try{
            $wechat = new Wechat(C('WX_PUBLIC_XinYChuang.token'), C('WX_PUBLIC_XinYChuang.appid'), C('WX_PUBLIC_XinYChuang.key'));
            //$wechat = new Wechat('weixin', 'wx0078c0d21d19e76b', ''); // 目前支付仅针对正式服务号
            $data = $wechat->request();
            \Think\Log::write(print_r($data,true));
            if($data && is_array($data)){
                file_put_contents('./data.json', json_encode($data));
                \Think\Log::write(print_r($data,true));
                $this->responseXinYChuang($wechat, $data);
            }
        } catch(\Exception $e){
            file_put_contents('./error.json', json_encode($e->getMessage()));
        }
    }

 

/**
     * 芯硬创
     */
    public function responseXinYChuang($wechat, $data){
        switch ($data['MsgType']) {
            case Wechat::MSG_TYPE_EVENT:
                switch ($data['Event']) {
                    case Wechat::MSG_EVENT_SUBSCRIBE://关注事件
                        \Think\Log::write($data);
                        // 裂变二维码关注

                        if (isset($data['EventKey']) && $data['Event'] == 'subscribe' && strrpos($data['EventKey'],"qrscene_liebian") !== false){
                            $EventKey = str_replace("qrscene_", "", $data['EventKey']);
                            \Think\Log::write($EventKey);
                            $fromOpenid = "";
                            if(strrpos($EventKey,"_@_") === false){
                                $EventKey = $EventKey;
                            }else{
                                list($EventKey,$fromOpenid) = explode("_@_",$EventKey);
                            }

                            \Think\Log::write($EventKey);
                            $WxQrConfigModel = D('WxQrConfig');

                            $openid = $data['FromUserName']; //必须先赋值,不然获取不了值
                            $this->addScanCounts($EventKey, $openid); // 扫码统计处理

                            $this->addScanScribe($EventKey, $openid); // 扫码关注统计处理

                            $map = array();
                            $map['scene_id'] = $EventKey;
                            $WxQrConfigModel->where($map)->setInc('count');

                            $info = $WxQrConfigModel->where($map)->find();
                            \Think\Log::write(print_r($info,true));
                            if($info){
                                $this->liebian($info,$wechat,$data,$fromOpenid);
                            }

                        }


                        /**
                         * 普通二维码关注回复
                         */
                        if (isset($data['EventKey'])){
                            $EventKey = str_replace("qrscene_", "", $data['EventKey']);
                            $WxQrConfigModel = D('WxQrConfig');

                            $openid = $data['FromUserName']; //必须先赋值,不然获取不了值
                            $this->addScanCounts($EventKey, $openid); // 扫码统计处理

                            $this->addScanScribe($EventKey, $openid); // 扫码关注统计处理

                            $map = array();
                            $map['scene_id'] = $EventKey;
                            $WxQrConfigModel->where($map)->setInc('count');
                            //根据是否有首关元素
                            //replyText 文本
                            //replyNewsOnce 图文
                            $info = $WxQrConfigModel->where($map)->find();
                            if($info){
                                $title = $info['title'];
                                $description = $info['description'];
                                $url = $info['url'];
                                $picture_url = $info['picture_url'];
                                $info['tt'] = 1;
                                // $this->logger($info);
                                if ($info['type'] == '3') { // 单图输出
                                    $wechat->replyImage($title);die;
                                }
                                if ($info['url'] && $info['title'] && $info['description'] && $info['picture_url']) {
                                    $wechat->replyNewsOnce($title, $description, $url, $picture_url);die;
                                } else if ($description) {
                                    $wechat->replyText($description);die;
                                }
                            }

                        }



                        //首次关注推送信息
                        $wechat->replyText(C("WX_PUBLIC_XinYChuang.first_desc"));die;

                        //首次关注推送信息
                        $WxReplyModel = new \Wechat\Model\WxReplyModel('wx_keyword','lie_','MKTWX_DB_CONFIG');
                        $res = $WxReplyModel->where("status = 1 and toUserType=2")->field("type,content")->limit(1)->order("create_time desc")->find();
                        if($res  && !empty($res)){
                            $content  = json_decode($res['content'],true);
                            $this->autoReply($res['type'],$wechat,$content,$data);
                        }else{
                            $wechat->replyText('欢迎关注芯硬件创客');die;
                        }
                        die;

                        break;
                    case Wechat::MSG_EVENT_UNSUBSCRIBE:
                        //取消关注,记录日志
                        $openid = $data['FromUserName']; //必须先赋值,不然获取不了值
                        $this->unsubscribe($openid);
                        break;
                    case Wechat::MSG_EVENT_CLICK:
                        // 自定义菜单点击事件
                        if (isset($data['EventKey'])){
                            $EventKey = str_replace("qrscene_", "", $data['EventKey']);
                            $WxQrConfigModel = D('WxQrConfig');

                            $map = array();
                            $map['scene_id'] = $EventKey;
                            $info = $WxQrConfigModel->where($map)->find();
                            $title = $info['title'];
                            $description = $info['description'];
                            $url = $info['url'];
                            $picture_url = $info['picture_url'];
                            if ($info['type'] == '3') { // 单图输出
                                $wechat->replyImage($title);die;
                            }
                            if ($info['url'] && $info['title'] && $info['description'] && $info['picture_url']) {
                                $wechat->replyNewsOnce($title, $description, $url, $picture_url);die;
                            } else if ($description) {
                                $wechat->replyText($description);die;
                            }
                        }
                        break;
                    case Wechat::MSG_EVENT_SCAN:  // 二维码扫描事件
                        if (isset($data['EventKey'])){
                            \Think\Log::write("----普通二维码扫描----");
                            //判断是否是裂变邀请二维码
                            $EventKey = str_replace("qrscene_", "", $data['EventKey']);
                            \Think\Log::write($EventKey);

                            $fromOpenid = "";//分享二维码的用户openid
                            if(strrpos($EventKey,"_@_") === false){
                                $EventKey = $EventKey;
                            }else{
                                list($EventKey,$fromOpenid) = explode("_@_",$EventKey);
                            }

                            $WxQrConfigModel = D('WxQrConfig');
                            // 扫码事件统计 wx_scan_history
                            $openid = $data['FromUserName']; //必须先赋值,不然获取不了值
                            $this->addScanCounts($EventKey, $openid); // 扫码统计处理

                            $map = array();
                            $map['scene_id'] = $EventKey;
                            $WxQrConfigModel->where($map)->setInc('count');
                            $info = $WxQrConfigModel->where($map)->find();
                            $title = $info['title'];
                            $description = $info['description'];
                            $url = $info['url'];
                            $picture_url = $info['picture_url'];
                            if(strrpos($data['EventKey'],"liebian_") !== false){
                                \Think\Log::write("----进入裂变----");
                                //如果是裂变扫码 邀请活动
                                $this->liebian($info,$wechat,$data,$fromOpenid,false);
                                die;
                            }



                            if ($info['type'] == '3') { // 单图输出
                                $wechat->replyImage($title);die;
                            }
                            if ($info['url'] && $info['title'] && $info['description'] && $info['picture_url']) {
                                $wechat->replyNewsOnce($title, $description, $url, $picture_url);die;
                            } else if ($description) {
                                $wechat->replyText($description);die;
                            }

                        }
                        break;
                    default:
                        break;
                }
                break;
            case Wechat::MSG_TYPE_TEXT:
                $WxKeywordModel = new \Wechat\Model\WxKeywordModel('wx_keyword','lie_','MKTWX_DB_CONFIG');
                $keyword = $data['Content'];
                $map['keyword'] = array('eq', $keyword);
                $map['status'] = array('eq', '1');
                $map['toUserType'] = array('eq', '1');
                $field = 'keyword,content,type,status';
                $res = $WxKeywordModel->field($field)->where($map)->find();
                if ($res) {
                    $content = json_decode($res['content'], true);
                    switch (strval($res['type'])) {
                        case '1': // 单文
                            $wechat->replyText($content['content']);die;
                            break;
                        case '2': // 图文
                            $wechat->replyNewsOnce($content['title'], $content['content'], $content['link'], $content['img']);die;
                            break;
                        case '3': // 单图
                            $wechat->replyImage($content['img']);die;
                            break;
                        case '4': // 复合
                            $wechatModel = wechat();
                            $openid = $data['FromUserName']; //必须先赋值,不然获取不了值

                            if ($content['content']) {
                                $redata = array(
                                    'touser' => $openid,
                                    "msgtype" => "text",
                                    "text" => array(
                                        'content' => $content['content'],
                                    ),
                                );
                                $wechatModel->sendCustomMessage($redata);
                            }
                            if ($content['contentsec']) {
                                $redata = array(
                                    'touser' => $openid,
                                    "msgtype" => "text",
                                    "text" => array(
                                        'content' => $content['contentsec'],
                                    ),
                                );
                                $wechatModel->sendCustomMessage($redata);
                            }

                            if ($content['img']) {
                                $redata['msgtype'] = 'image';
                                $redata['touser'] = $openid;
                                $redata['image'] = array(
                                    'media_id' => $content['img'],
                                );
                                $wechatModel->sendCustomMessage($redata);
                            }


                            break;
                        default:
                            # code...
                            break;
                    }

                } else {
                    if($this->autoReplyLimit($data)) die;

                    $WxReplyModel = new \Wechat\Model\WxReplyModel('wx_keyword','lie_','MKTWX_DB_CONFIG');
                    $res = $WxReplyModel->where("status = 1 and toUserType=3")->field("type,content")->limit(1)->order("create_time desc")->find();
                    if($res  && !empty($res)){
                        $content  = json_decode($res['content'],true);
                        $this->SetAutoReplyLimit($data);
                        $this->autoReply($res['type'],$wechat,$content,$data);
                    }
//                        $wechat->replyText('暂无此关键词相关信息~_~');
                    $this->SetAutoReplyLimit($data);
                    die;
                }

                break;
            default:
                # code...
                break;
        }
    }

 

 

/**

* 事件类型常量

*/

const MSG_EVENT_SUBSCRIBE = 'subscribe';

const MSG_EVENT_UNSUBSCRIBE = 'unsubscribe';

const MSG_EVENT_SCAN = 'SCAN';

const MSG_EVENT_LOCATION = 'LOCATION';

const MSG_EVENT_CLICK = 'CLICK';

const MSG_EVENT_VIEW = 'VIEW';


/**

* 消息类型常量

*/

const MSG_TYPE_TEXT = 'text';

const MSG_TYPE_IMAGE = 'image';

const MSG_TYPE_VOICE = 'voice';

const MSG_TYPE_VIDEO = 'video';

const MSG_TYPE_SHORTVIDEO = 'shortvideo';

const MSG_TYPE_LOCATION = 'location';

const MSG_TYPE_LINK = 'link';

const MSG_TYPE_MUSIC = 'music';

const MSG_TYPE_NEWS = 'news';

const MSG_TYPE_EVENT = 'event';


本文中消息类型处理主要分 事件(event)和文本(text)




event分为:


    1,首次关注:

case Wechat::MSG_EVENT_SUBSCRIBE://关注事件

///临时代码 by long  抽奖
                            try{
                                \Think\Log::write(json_encode($data));
                                if(isset($data['Event']) && $data['Event'] == 'subscribe' && strrpos($data['EventKey'],"qrscene_choujiang-") !== false ){
                                    list(,$user_id,$lottery_id) = explode("-",$data['EventKey']);
                                    $k1 = time();
                                    $res = post_curl(API_DOMAIN.'/Activity/Lottery/increaseQualifyByFollow', [
                                        'lottery_id'=>intval($lottery_id),
                                        'pf'=>3,
                                        'user_id'=>$user_id,
                                        'k1'=>$k1,
                                        "k2"=>md5(md5($k1).C('SUPER_AUTH_KEY'))
                                    ]);
                                    \Think\Log::write($res);
                                    $choujiang_config = C('CHOU_JIANG');
                                    \Think\Log::write(json_encode($choujiang_config));
                                    $wechat->replyNewsOnce($choujiang_config['title'],
                                        $choujiang_config['des'], $choujiang_config['url'],
                                        $choujiang_config['img']);
                                    die;
                                }
                            }catch(\Exception $e){

                            }


                            /**
                             * 普通二维码关注回复
                             */
                            if (isset($data['EventKey'])){
                                $EventKey = str_replace("qrscene_", "", $data['EventKey']);
                                $WxQrConfigModel = D('WxQrConfig');

                                $openid = $data['FromUserName']; //必须先赋值,不然获取不了值
                                $this->addScanCounts($EventKey, $openid); // 扫码统计处理

                                $this->addScanScribe($EventKey, $openid); // 扫码关注统计处理

                                $map = array();
                                $map['scene_id'] = $EventKey;
                                $WxQrConfigModel->where($map)->setInc('count');
                                //根据是否有首关元素
                                //replyText 文本
                                //replyNewsOnce 图文
                                $info = $WxQrConfigModel->where($map)->find();
                                if($info){
                                    $title = $info['title'];
                                    $description = $info['description'];
                                    $url = $info['url'];
                                    $picture_url = $info['picture_url'];
                                    $info['tt'] = 1;
                                    // $this->logger($info);
                                    if ($info['type'] == '3') { // 单图输出
                                        $wechat->replyImage($title);die;
                                    }
                                    if ($info['url'] && $info['title'] && $info['description'] && $info['picture_url']) {
                                        $wechat->replyNewsOnce($title, $description, $url, $picture_url);die;
                                    } else if ($description) {
                                        $wechat->replyText($description);die;
                                    }
                                }

                            }




                            //首次关注推送信息


                            $WxReplyModel = new \Wechat\Model\WxReplyModel('wx_keyword','lie_','MKTWX_DB_CONFIG');
                            $res = $WxReplyModel->where("status = 1 and toUserType=2")->field("type,content")->limit(1)->order("create_time desc")->find();
                            if($res  && !empty($res)){
                                $content  = json_decode($res['content'],true);
                                $this->autoReply($res['type'],$wechat,$content,$data);
                            }else{
                                $wechat->replyText('欢迎关注猎芯网');die;
                            }
                            die;

//                            $title = C('WX_PUBLIC.first_title');
//                            $discription = C('WX_PUBLIC.first_desc');
//                            $url = C('WX_PUBLIC.first_url');
//                            $picurl = C('WX_PUBLIC.first_img');
////                            $wechat->replyText($title);die;
//                            $wechat->replyNewsOnce($title, $discription, $url, $picurl);die;

                            break;
View Code

 

CREATE TABLE `lie_wx_qr_config` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT COMMENT 'ID',
  `count` mediumint(8) unsigned NOT NULL DEFAULT '0' COMMENT '渠道统计(每次关注后新增一次)',
  `qrurl` varchar(255) NOT NULL DEFAULT '' COMMENT '追踪二维码链接地址',
  `qrurl_logo` varchar(255) DEFAULT '' COMMENT '带logo的二维码',
  `scene_id` varchar(255) NOT NULL DEFAULT '' COMMENT '自定义追踪id(可为数字或字符串)',
  `create_time` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '创建时间',
  `expire_seconds` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '临时二维码有效期,最大为604800秒',
  `type` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '类型,0:临时二维码;1:数值型永久二维码(此时expire_seconds参数无效);2:字符串型永久二维码(此时expire_seconds参数无效) 3单图',
  `title` varchar(255) NOT NULL DEFAULT '' COMMENT '标题',
  `media_id_url` varchar(200) NOT NULL DEFAULT '' COMMENT '微信图片的url地址',
  `url` varchar(255) NOT NULL DEFAULT '' COMMENT '点击链接',
  `picture_url` varchar(255) NOT NULL DEFAULT '' COMMENT '图片链接地址',
  `description` varchar(255) NOT NULL DEFAULT '' COMMENT '描述文本',
  `scene_desc` varchar(255) NOT NULL DEFAULT '' COMMENT '渠道标识',
  `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态(-1已删除 1展示)',
  `lottery_id` int(11) unsigned NOT NULL DEFAULT '0' COMMENT '关联活动id',
  `wetch_com_id` tinyint(3) unsigned NOT NULL DEFAULT '1' COMMENT '1猎芯  2芯片硬创',
  `qrcode_use` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '1普通二维码  2裂变',
  PRIMARY KEY (`id`),
  KEY `scene_id` (`scene_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=93 DEFAULT CHARSET=utf8 COMMENT='微信自定义追踪二维码';

 

 

 

 

 改后台主要生成二维码事件记录表 主要通过事件scene_id来查找该二维码要触发的动作     单图,文本  图片等

 

 

 /**
                             * 普通二维码关注回复
                             */
                            if (isset($data['EventKey'])){
                                $EventKey = str_replace("qrscene_", "", $data['EventKey']);
                                $WxQrConfigModel = D('WxQrConfig');

                                $openid = $data['FromUserName']; //必须先赋值,不然获取不了值
                                $this->addScanCounts($EventKey, $openid); // 扫码统计处理

                                $this->addScanScribe($EventKey, $openid); // 扫码关注统计处理

                                $map = array();
                                $map['scene_id'] = $EventKey;
                                $WxQrConfigModel->where($map)->setInc('count');
                                //根据是否有首关元素
                                //replyText 文本
                                //replyNewsOnce 图文
                                $info = $WxQrConfigModel->where($map)->find();
                                if($info){
                                    $title = $info['title'];
                                    $description = $info['description'];
                                    $url = $info['url'];
                                    $picture_url = $info['picture_url'];
                                    $info['tt'] = 1;
                                    // $this->logger($info);
                                    if ($info['type'] == '3') { // 单图输出
                                        $wechat->replyImage($title);die;
                                    }
                                    if ($info['url'] && $info['title'] && $info['description'] && $info['picture_url']) {
                                        $wechat->replyNewsOnce($title, $description, $url, $picture_url);die;
                                    } else if ($description) {
                                        $wechat->replyText($description);die;
                                    }
                                }

                            }
View Code

 




2, 取消关注
case Wechat::MSG_EVENT_UNSUBSCRIBE:


3, 自定义菜单点击事件

case Wechat::MSG_EVENT_CLICK:
// 自定义菜单点击事件
                            if (isset($data['EventKey'])){
                                $EventKey = str_replace("qrscene_", "", $data['EventKey']);
                                $WxQrConfigModel = D('WxQrConfig');

                                $map = array();
                                $map['scene_id'] = $EventKey;
                                $info = $WxQrConfigModel->where($map)->find();
                                $title = $info['title'];
                                $description = $info['description'];
                                $url = $info['url'];
                                $picture_url = $info['picture_url'];
                                if ($info['type'] == '3') { // 单图输出
                                    $wechat->replyImage($title);die;
                                }
                                if ($info['url'] && $info['title'] && $info['description'] && $info['picture_url']) {
                                    $wechat->replyNewsOnce($title, $description, $url, $picture_url);die;
                                } else if ($description) {
                                    $wechat->replyText($description);die;
                                }
                            }
                            break;
View Code

 




4,// 二维码扫描事件
case Wechat::MSG_EVENT_SCAN:  
if (isset($data['EventKey'])){
                                $EventKey = str_replace("qrscene_", "", $data['EventKey']);
                                $WxQrConfigModel = D('WxQrConfig');
                                // 扫码事件统计 wx_scan_history
                                $openid = $data['FromUserName']; //必须先赋值,不然获取不了值
                                $this->addScanCounts($EventKey, $openid); // 扫码统计处理

                                $map = array();
                                $map['scene_id'] = $EventKey;
                                $WxQrConfigModel->where($map)->setInc('count');
                                $info = $WxQrConfigModel->where($map)->find();
                                $title = $info['title'];
                                $description = $info['description'];
                                $url = $info['url'];
                                $picture_url = $info['picture_url'];
                                // $this->logger($info);


                                if ($info['type'] == '3') { // 单图输出
                                    $wechat->replyImage($title);die;
                                }
                                if ($info['url'] && $info['title'] && $info['description'] && $info['picture_url']) {
                                    $wechat->replyNewsOnce($title, $description, $url, $picture_url);die;
                                } else if ($description) {
                                    $wechat->replyText($description);die;
                                }

                            }
                            break;
View Code

 




5,自动回复
case Wechat::MSG_TYPE_TEXT: //自动回复
$WxKeywordModel = new \Wechat\Model\WxKeywordModel('wx_keyword','lie_','MKTWX_DB_CONFIG');
                    $keyword = $data['Content'];
                    $map['keyword'] = array('eq', $keyword);
                    $map['status'] = array('eq', '1');
                    $map['toUserType'] = array('eq', '1');
                    $field = 'keyword,content,type,status';
                    $res = $WxKeywordModel->field($field)->where($map)->find();
                    if ($res) {
                        $content = json_decode($res['content'], true);
                        switch (strval($res['type'])) {
                            case '1': // 单文
                                $wechat->replyText($content['content']);die;
                                break;
                            case '2': // 图文
                                $wechat->replyNewsOnce($content['title'], $content['content'], $content['link'], $content['img']);die;
                                break;
                            case '3': // 单图
                                $wechat->replyImage($content['img']);die;
                                break;
                            case '4': // 复合
                                $wechatModel = wechat();
                                $openid = $data['FromUserName']; //必须先赋值,不然获取不了值

                                if ($content['content']) {
                                    $redata = array(
                                        'touser' => $openid,
                                        "msgtype" => "text",
                                        "text" => array(
                                            'content' => $content['content'],
                                        ),
                                    );
                                    $wechatModel->sendCustomMessage($redata);
                                }
                                if ($content['contentsec']) {
                                    $redata = array(
                                        'touser' => $openid,
                                        "msgtype" => "text",
                                        "text" => array(
                                            'content' => $content['contentsec'],
                                        ),
                                    );
                                    $wechatModel->sendCustomMessage($redata);
                                }

                                if ($content['img']) {
                                    $redata['msgtype'] = 'image';
                                    $redata['touser'] = $openid;
                                    $redata['image'] = array(
                                        'media_id' => $content['img'],
                                    );
                                    $wechatModel->sendCustomMessage($redata);
                                }


                                break;
                            default:
                                # code...
                                break;
View Code

 

 

 












 

本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/articles/12689710.html

posted on 2020-04-13 10:17  孙龙-程序员  阅读(183)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3