微信公众号自动回复图片

        关于微信公众号自动回复图片,有5个参数,如下:

其中最重要的是media_id,没有media_id其他都是空谈。

reply_image数据表:
rule数据表:
rule数据表相当于对文本,图片,图文的整合。

在replyimage方法中写“回复图片”的相关代码
<?php
//回复图片
	public function replyimage(){
		$url = I('post.url');
		$keyword = I('post.keyword');
		$media_id = I('post.media_id');
		if(empty($keyword) || empty($url)){
			$this->ajaxReturn(array('status'=>0,'msg'=>'必须输入关键字和选择图片'));
			exit;
		}

		//判断$media_id是否为空
		if (empty($media_id)) {
			$accessToken = getAccess_token();
			include APP_PATH . 'LaneWeChat/lanewechat.php';

			$api = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=$accessToken&type=image";
			$file = realpath($url);
			$data['media'] = Curl::addFile($file);
			$ret = Curl::callWebServer($api,$data,'post',1,0);
			// $this->ajaxReturn($ret);
			//检测$media_id是否设置
			if (isset($ret['media_id'])) {
				$media_id = $ret['media_id'];
				$url = $ret['url'];
			}else{
				$ret['fail'] = "出错啦";
				$this->ajaxReturn(array('status'=>1,'msg'=>$ret));
				exit;
			}
		}
		$data['media_id'] = $media_id;
		$data['url'] = $url;
		$reply_id = M('mp_reply_image')->add($data);

		$mp = getCurrentMp();
		$mpid = $mp['id'];
		
		$arr['mpid']=$mpid;
		$arr['reply_id'] = $reply_id;
		$arr['keyword']=$keyword;
		$arr['type']='image';
		$result = M('mp_rule')->add($arr);
		if ($result) {
			$this->ajaxReturn(array('status'=>1,'msg'=>'添加成功'));
		}else{
			$this->ajaxReturn(array('status'=>0,'msg'=>'添加失败'));
		}
	}
?>
当自动回复图片时,replyimage中调用的text方法代码如下:
<?php 
public static function text(&$request){
        $mpid = $_GET['id'];
        $content = $request['content'];
        $where['mpid'] = $mpid;
        $where['keyword'] = $content;
        $data = M('mp_rule')->where($where)->find();
        if ($data) {
            //发送关键字
            $reply_id = $data['reply_id'];
            $type = $data['type'];
            switch ($type) {
                case 'image':
                    $reply = M('mp_reply_image')->find($reply_id);
                    if ($reply) {
                        $media_id = $reply['media_id'];
                        return ResponsePassive::image($request['fromusername'],$request['tousername'],$media_id);
                    }else{
                        $reply_text = "出错了";
                        return ResponsePassive::text($request['fromusername'],$request['tousername'],$reply_text);
                    }
                    break;
                default:
                    return "success";
                    break;
            }
        }else{
             return "success";
        }
    }
?>

猜你喜欢

转载自blog.csdn.net/qwy0419/article/details/80265249