微信公众号开发 同时回复用户多条信息(包括图片和文字)

本文介绍如何在微信公众号中实现点击菜单后向用户发送多条消息的功能,包括文本消息和图片消息。文章详细展示了从创建菜单、获取Access Token到发送定制消息的全过程。

相信对于大多数的微信公众号开发的初学者来说,由于微信提供的文档过于简洁,所以这无疑是对我们的巨大考验。

但是,苦心人,天不负。在强烈的“我能行”这一自我暗示下,经过在各大网站上的查询、电子书籍类的读阅,经过无数次的尝试,终于能够实现一次事件同时回复用户多条信息的功能了。额,不说废话了,下面展示我的最终成果。 

(公众号是接管过来自己开发的)

首先,创建公众号子菜单的点击事件

const APPID = '你的微信appid';
	const SECRET = '你的secret';
	const ACCESS_TOKEN_URL = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=';
	const GET_MENU_URL = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token=';
	const CREATE_MENU_URL = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=';


/** 
	* createmenu 
	* 创建菜单 
	* @access public 
	* @param void
	* @since 1.0 
	* @return array 
	*/ 
	public function actioncreatemenu()
	{
		$access_token_url = self::ACCESS_TOKEN_URL.self::APPID.'&secret='.self::SECRET;
		$wdata =json_decode($this->curl_get($access_token_url),true);
		$create_menu_url = self::CREATE_MENU_URL.$wdata['access_token'];
		$menu = json_encode($this->getMenuConfig(),JSON_UNESCAPED_UNICODE);
		$data = $this->curl_post($create_menu_url,$menu);
		echo $data;exit;
	}
private function getMenuConfig()
	{
		$data = array();
		$data = Array(

				'button' => Array(
						 Array(
							'name' => '你关心的',
							'sub_button' => Array(
										Array(
											'type' => 'click',
											'name' => '邀友有礼',
											'key' => 'V1001_INVITE_GIFT'
											)
														
										)
							)
)
}

public function curl_post($url, $data)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$output = curl_exec($ch);
		if (curl_errno($ch)) {
		return curl_error($ch);
		}

		curl_close($ch);
		return $output;

	}


然后在网页运行 createmenu方法,微信公众号菜单就创建好了。

这些都是前期的准备。

下面是点击事件的处理

$this->sendIMG($media_id , $open_id , $token);
这行代码中的 media_id ,是通过微信接口上传媒体素材返回的微信独有的标识,上传素材的代码在最后面展示

	libxml_disable_entity_loader(true);
        $postObj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
        $fromUsername = $postObj->FromUserName;
        $toUsername = $postObj->ToUserName;
        $event = $postObj->Event;
        $time = $postObj->CreateTime;
	$open_id = trim($fromUsername);
	$MsgType = $postObj->MsgType;
	file_put_contents('/tmp/test.log', $MsgType, FILE_APPEND);
switch ($event) {
case 'CLICK':
			$token = $this->token();
			$this->sendText($open_id , $token);
				
			$resultIMG = '图片相对于服务器下的路径';
			$media_id = $this->add_m($resultIMG);
			$this->sendIMG($media_id , $open_id , $token);
			/*	
			$returnTpl = "<xml>
					<ToUserName><![CDATA[%s]]></ToUserName>
					<FromUserName><![CDATA[%s]]></FromUserName>
					<CreateTime>%s</CreateTime>
					<MsgType><![CDATA[%s]]></MsgType>
					<Image>
						<MediaId><![CDATA[%s]]></MediaId>
					</Image>
				</xml>";
			$resultStr = sprintf($returnTpl,$fromUsername , $toUsername , time(), 'image'  ,$media_id);
			echo $resultStr;	*/			
		break;
}

function sendText($open_id , $token) {
		$data = '{ "touser" : "'.$open_id.'",
						"msgtype" : "text",
						"text" : {
							"content" : "敬请期待" 
						}
					}';
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$token;
		$result = $this->https_request($url , $data);
		var_dump($result);
	}
	
	function sendIMG($media_id , $open_id , $token) {
		$data = '{ "touser" : "'.$open_id.'",
						"msgtype" : "image",
						"image" : {
							"media_id" : "'.$media_id.'" 
						}
					}';
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$token;
		$result = $this->https_request($url , $data);
		var_dump($result);
	}

上传媒体素材,这里上传的是图片,所以传的参数则是一张图片的路径

function add_m($img) {
		
		$path = '这里填写图片上传的相对路径'.$img ;  
		//$img = 'web/image/qrcode/20161229/10.jpg';
		if (class_exists ( '\CURLFile' )) {//关键是判断curlfile,官网推荐php5.5或更高的版本使用curlfile来实例文件  
			$filedata = array (  
				'fieldname' => new \CURLFile ( realpath ( $path ), 'image/jpeg' )   
			);  
		} else {  
			$filedata = array (  
				'fieldname' => '@' . realpath ( $path )   
			);  
		}  
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->token()."&type=image";
        $result = $this->https_request($url , $filedata);
		$data = json_decode($result);
       return $data->media_id;
}
(通过 path ,必须能够在服务器下访问到图片)


最后,说明一下,我的图片是能都通过网络访问到的,比如(http://www.image.****.com)

但是,当我将这个图片的地址添加到上传媒体素材进行上传的时候,结果是上传失败,也就没有了本来应该返回的 media_id,所以采用了获取路径上传的方法

在这里如果有更好的方法,欢迎留言艾特我,大家相互交流,共同进步!!!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值