贴一段微信公众平台发送模板消息的代码

原创
2016-06-07 11:41:00 989浏览

贴一段微信公众平台发送模板消息的代码,网上有关这方面的资料比较少,本人亲测以后分享出来,供新手学习交流!
第一步:先构造一个向远程服务器提交数据的函数
//构造一个请求函数
function http_request($url,$data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// 我们在POST数据哦!
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
第二步:正式开始
public function sendtpl_msg(){
$appid="wxa46e292d23a7104b";
$appsecret="24feffbfce0ad7b3868345c96cf6eae5";
$json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret);
$access_token=json_decode($json_token,true);
//获得access_token
$this->access_token=$access_token[access_token];
//echo $this->access_token;exit;
//模板消息
$template=array(
'touser'=>$_GET['wecha_id'],
'template_id'=>"vkz0BNTIgSbXfuJkcKdGl_FvL9qSKsqeWeCfIkQ1DY4",
'url'=>"http://weixin.qq.com/download",
'topcolor'=>"#7B68EE",
'data'=>array(
'first'=>array('value'=>urlencode("您好,您已购买成功"),'color'=>"#743A3A"),
'name'=>array('value'=>urlencode("商品信息:微时代电影票"),'color'=>'#EEEEEE'),
'remark'=>array('value'=>urlencode('永久有效!密码为:1231313'),'color'=>'#FFFFFF'),
)
);
$json_template=json_encode($template);
//echo $json_template;
//echo $this->access_token;
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
$res=http_request($url,urldecode($json_template));
if ($res[errcode]==0) echo '模板消息发送成功!';
//print_r($res);

}

AD:真正免费,域名+虚机+企业邮箱=0元

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。