前阵子小程序项目中因为需要及时通知用户,就打算对接小程序的模板通知.可是说是小程序在明年的一月份就不支持了.所以就放下了.
今天有需要在公众号中发送模板消息.也是直接看了下文档直接来对接起来.也是很顺利.
首先,需要去公众号后台申请模板.
在微信公众平台-功能-模板消息里面申请.选择自己需要选择的分类.保存下模板id.
这里自己也是简单封装下.为以后需要作准备.这里简单分享下.
需要注意的是这里的Accesstoken 你需要根据根据自己的情况来保存一下.因为这个东西每天只有2000次的获取次数.保存到缓存或者数据库都可以.这里做最简单的分享
/**
公众号模板消息
* $openid 需要发送用户的openid
* $name 用户名字
* $mobile 联系方式
* $time 派单时间
* $content 维修内容
*/
public function templateInfo($openid,$name,$mobile,$time,$content)
{
$ACCESS_TOKEN = $this->getAccessToken();//通过微信获取access_token接口 获取的token
// $openid = '';//用户openid
$template_id = '';//配置的模板id
$url = '';//点击模板消息跳转的链接
$template = array(
'touser' => $openid,
'template_id' => $template_id,
'url' => $url,
'data' => array(
'first' => array('value' => '您好,您有新的维修任务!', 'color' => "#173177"),
'keyword1' => array('value' => $name, 'color' => '#173177'),
'keyword2' => array('value' => $mobile, 'color' => '#173177'),
'keyword3' => array('value' => $time, 'color' => '#173177'),
'keyword4' => array('value' => $content, 'color' => '#173177'),),
'remark' => array('value' => '请及时登录公众号接单确认!', 'color' => "#173177")
);
$send_template_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $ACCESS_TOKEN;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $send_template_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($template));
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$res = curl_exec($ch);
curl_close($ch);
return $res;
}
/**
* 获取access_token
*/
public function getAccessToken()
{
$appId = db('config')->where(['name' => 'appid'])->value('value');
$appSecret = db('config')->where(['name' => 'appsearct'])->value('value');
$tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
$getArr=array();
$tokenArr=json_decode($this->send_post($tokenUrl,$getArr,"GET"));
$access_token=$tokenArr->access_token;
return $access_token;
}
/**
* 请求方法
*/
protected function send_post($url, $post_data,$method='POST')
{
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => $method, //or GET
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $postdata,
'timeout' => 15 * 60 // 超时时间(单位:s)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
用的时候直接调用templateInfo
这个方法传入对应的参数就行. ?
效果如图下所示
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有