微信公众号——自动回复

先建表 mp_reply_rule(用于存放关键字),mp_reply_news(用于存放文本标题,内容,图片链接),传到数据库中  

之后 获取access_token,获取微信服务器地址,在微信公众测试号上面配置微信,

获取到标题,文本,图片等内容,并将获取到的内容加入到数据库,选择本地图片,并上传到数据库。

public function addNews(){  
      $keyword=I('post.keyword');  
     $title=I('post.title');   
     $media_id=I('post.media_id');  
     $url=I('post.url');  
     $content=I('post.content');  
     $content_source_url=I('post.content_source_url');  
       // dump($media_id);  
       // exit;  
  
  
       if(empty($keyword)|| empty($url)){  
            $this->ajaxReturn(array('status'=>0,'msg'=>'必须输入关键字和选择图片'));  
            exit;  
       }  
       //选择本地图片,需上传到公众平台  
       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);  
            // dump($file);  
            // exit;  
            $data['media']= '@' .$file;  
            $ret=Curl::callWebServer($api,$data,'post',1,0);  
  
            //上传成功  
            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['picurl']=$url;  
     $data['title']=$title;  
     $data['media_id']=$media_id;  
     $data['description']=$content;  
     $data['url']=$content_source_url;  
     $reply_id=M('mp_reply_news')->add($data);  
  
     $mp=getCurrentMp();  
     $arr['mp_id']=$mp['id'];  
     $arr['type']='news';  
     $arr['keyword']=$keyword;  
     $arr['reply_id']=$reply_id;  
     $ret=M('mp_rule')->add($arr);  
       if($ret){  
            $this->ajaxReturn(array('status'=>1,'msg'=>'添加成功','url'=>U('replynews',['type'=>'image'])));  
       }else{  
            $this->ajaxReturn(array('status'=>1,'msg'=>'添加失败'));  
       }  
   }  
  
 

之后在写upload 方法上传文件

  //接受文件上传  
 public function upload(){  
     $upload = new \Think\Upload();// 实例化上传类  
     $upload->maxSize = 3145728 ;// 设置附件上传大小  
     $upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型  
     $upload->rootPath = './Uploads/'; // 设置附件上传根目录  
     $upload->savePath = ''; // 设置附件上传(子)目录  
     // 上传文件  
     $info = $upload->uploadOne($_FILES['file']);  
    if(!$info) {// 上传错误提示错误信息  
       // $this->error($upload->getError());  
         $this->ajaxReturn(array('code'=>'1','msg'=>$upload->getError()));  
     }else{// 上传成功  
       // $this->success('上传成功!');  
         $file="/Uploads/".$info['savepath'].$info['savename'];;  
         $this->ajaxReturn(array('code'=>'0','msg'=>"上传成功!",'url'=>$file));  
     }  
}  

猜你喜欢

转载自blog.csdn.net/lixiaotong_123/article/details/80012088