微信公众平台发送模板消息
模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。
步骤如下:
1.先构造一个向远程服务器提交数据的函数
构造方法参见:PHP中的curl网络请求
2.获取模板消息的模板ID和结构
登录微信公众号后台查看,如下图
3.正式开始
- //发送模板消息
- public function sendtemplate($data){
- $curl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$this->_getAccessToken();
- $content = $this->_request($curl,true,'POST',$data);
- $result = json_decode($content,true);
- return $result;
- }
- $template=array(
- 'touser'=>'o5-fcwWKi4-3145iNUS2wqZ8PdFo',
- 'template_id'=>"wTcg5P5ggyJZPWFGs7PYt0lJVCNK05H59ZaSPynJErg",
- 'url'=>"http://www.topthink.com/topic/11991.html",
- 'topcolor'=>"#7B68EE",
- 'data'=>array(
- 'first'=>array('value'=>urlencode("恭喜你购买成功!"),'color'=>"#FF0000"),
- 'keyword1'=>array('value'=>urlencode('牛奶巧克力'),'color'=>'#FF0000'),
- 'keyword2'=>array('value'=>urlencode('Venta'),'color'=>'#FF0000'),
- 'keyword3'=>array('value'=>urlencode('100.00元'),'color'=>'#FF0000'),
- 'keyword4'=>array('value'=>urlencode('98.00元'),'color'=>'#FF0000'),
- 'keyword5'=>array('value'=>urlencode(date("Y-m-d H:i:s")),'color'=>'#FF0000'),
- 'remark'=>array('value'=>urlencode('欢迎再次购买!'),'color'=>'#FF0000'),
- )
- );
- $result = $wechat->sendtemplate(urldecode(json_encode($template)));
其中的touser,template_id和url分别是接收消息者的openid,模板ID和模板点开之后的url,开发中需要动态赋值!