微信也可以通过发送文字然后回复图片消息。
代码如下:
public function replyImage(){
if(IS_GET){
$this->display();
}else{
$keyword=I('post.keyword');
$media_id=I('media_id');
$url=I('post.url');//图片在本地服务器上的路径
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';
$url1="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=$accessToken&type=image";
$file=realpath('.'. $url);//相对路径->绝对路径
// dump($file);
// exit;
$data['media']=Curl::addFile($file);
$ret=Curl::callWebServer($url1,$data,'post',1,0);
if(isset($ret['media_id'])){
$media_id=$ret['media_id'];
$url=$ret['url'];
// dump($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();
$arr=array(
'mpid'=>$mp['id'],
'type'=>'image',
'keyword'=>$keyword,
'reply_id'=>$reply_id
);
$ret=M('mp_rule')->add($arr);
if($ret){
// $this->ajaxReturn(array('status'=>1,'msg'=>'添加成功','url'=>U('keywords',['type'=>'image'])));
$this->ajaxReturn(array('status'=>1,'msg'=>'添加成功','url'=>U('replyimage')));
}else{
$this->ajaxReturn(array('status'=>1,'msg'=>'添加失败'));
}
}
}
}
当然图片需要从本地进行上传,所以,上传的方法是从前台调用的。
此处需要注意的是添加数据进入数据库,数据库的rule表的reply_id是需要与image表的reply_id相同。一一对应,才能回复正确的信息。
回复图片是需要使用media_id的,图片上传成功返回media_id,调用微信回复图片的接口,即可成功。