微信公众平台发送模板消息

来源:互联网 发布:ubuntu 14 搜狗输入法 编辑:程序博客网 时间:2024/04/24 01:44

模板消息仅用于公众号向用户发送重要的服务通知,只能用于符合其要求的服务场景中,如信用卡刷卡通知,商品购买成功通知等。

步骤如下:

1.先构造一个向远程服务器提交数据的函数

构造方法参见:PHP中的curl网络请求

2.获取模板消息的模板ID和结构

登录微信公众号后台查看,如下图


3.正式开始

[php] view plain copy
  1. //发送模板消息  
  2. public function sendtemplate($data){  
  3.       
  4.     $curl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$this->_getAccessToken();  
  5.       
  6.     $content = $this->_request($curl,true,'POST',$data);  
  7.     $result = json_decode($content,true);  
  8.       
  9.     return $result;  
  10. }  
其中data构造如下:
[php] view plain copy
  1. $template=array(  
  2.     'touser'=>'o5-fcwWKi4-3145iNUS2wqZ8PdFo',  
  3.     'template_id'=>"wTcg5P5ggyJZPWFGs7PYt0lJVCNK05H59ZaSPynJErg",  
  4.     'url'=>"http://www.topthink.com/topic/11991.html",  
  5.     'topcolor'=>"#7B68EE",  
  6.     'data'=>array(  
  7.         'first'=>array('value'=>urlencode("恭喜你购买成功!"),'color'=>"#FF0000"),  
  8.         'keyword1'=>array('value'=>urlencode('牛奶巧克力'),'color'=>'#FF0000'),  
  9.         'keyword2'=>array('value'=>urlencode('Venta'),'color'=>'#FF0000'),  
  10.         'keyword3'=>array('value'=>urlencode('100.00元'),'color'=>'#FF0000'),  
  11.         'keyword4'=>array('value'=>urlencode('98.00元'),'color'=>'#FF0000'),  
  12.         'keyword5'=>array('value'=>urlencode(date("Y-m-d H:i:s")),'color'=>'#FF0000'),  
  13.         'remark'=>array('value'=>urlencode('欢迎再次购买!'),'color'=>'#FF0000'),  
  14.     )  
  15. );  
  16. $result = $wechat->sendtemplate(urldecode(json_encode($template)));  

其中的touser,template_id和url分别是接收消息者的openid,模板ID和模板点开之后的url,开发中需要动态赋值!
原创粉丝点击