此次和上一篇:微信公众号上传素材类似,这里部分代码就省略
直接上代码:
创建自定义菜单:
public function menu(){$bb=["button"=>[[ "type"=>"click","name"=>"生成海报","key"=>"qrcode001"//这里要记住,后面要用到此key值],["type"=>"view","name"=>"搜索","url"=>"/index.php/index/wx"]]];$postdata=json_encode($bb,JSON_UNESCAPED_UNICODE);//JSON_UNESCAPED_UNICODE 解析中文$url='https://api./cgi-bin/menu/create?access_token='.$this->get_access_token();$info=$this->_request($url,true,'post',$postdata);var_dump($info);//$info返回值 {"errcode":0,"errmsg":"ok"}}
公众号接受用户发来的数据:
public function responseMsg(){$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];if (!empty($postStr)){$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);$RX_TYPE = trim($postObj->MsgType);//点击自定义菜单发送海报给用户if($RX_TYPE=='event'){if(trim($postObj->Event)=='CLICK'){$resultStr = $this->handleoneimg($postObj);echo $resultStr;}}else {echo "";exit;}}}
发送图片给用户:
//自定义菜单点击click,公众号发送 图片 public function handleoneimg($postObj){$fromUsername = $postObj->FromUserName;$toUsername = $postObj->ToUserName;$EventKeytrim=trim($postObj->EventKey);//点击自定义菜单click时的key值$time = time();$textTpl="<xml><ToUserName><![CDATA[%s]]></ToUserName><FromUserName><![CDATA[%s]]></FromUserName><CreateTime>%s</CreateTime><MsgType><![CDATA[image]]></MsgType><Image><MediaId><![CDATA[%s]]></MediaId></Image></xml>";//调用上传素材的方法$this->uploadImg()$res=json_decode($this->uploadImg(),true);//判断点击自定义菜单click时key值与自定义菜单的key是否相同if($EventKeytrim=='qrcode001'){$mediaid=$res['media_id'];$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $mediaid);return $resultStr;}}
最终效果图: