原文链接:https://www.whongbin.cn/index/article/detail/id/49.html
前言
上篇文章咱们说了下在微信小程序中发送业务通知的方法,今天咱们再来聊聊微信公众号中的业务通知----微信模板消息.
开发准备
在微信开发中,不少刚接触微信开发的同僚一直搞不清楚这些名词:个人订阅号、认证的订阅号、服务号、认证的服务号,搞不清楚什么呢,搞不清楚哪个账号有哪些接口调用的权限?其他的不说了,今天咱们聊的是微信模板消息,就说说这个吧.
- 模板消息是 高级接口 ,所以需要 认证后的服务号 才可开通模板消息权限
- 开通模板消息权限时,需要选择公众账号服务所处的2个行业,每月可更改1次所选行业
- 每个账号最多可以同时使用 25个模板 ,请提前选择要使用的模板
- 其他需要准备的就是微信公众号的 APPID 和 APPSecret 了
相关配置
https://ws1.sinaimg.cn/large/0064eL5bly1fwxafti57bj31610cumye.jpg进到公众号中后,在左侧菜单中找到添加功能插件
https://ws1.sinaimg.cn/large/0064eL5bly1fwxai6fmd9j30l809uwfi.jpg添加模板消息功能
https://ws1.sinaimg.cn/large/0064eL5bly1fwxajmj8s0j30qp0k1gni.jpg申请开通模板消息权限时,需要选择公众账号服务所处的2个行业,每月可更改1次所选行业
注意:在申请完成后,会有一些参数要用(上图中箭头所指的地方),运营者最好截图给开发人员或直接让开发人员去申请,参数错误的话会出现模板消息发送失败
代码实现
微信模板消息通用类
<?php
namespace Whb\Weixin;
/**
* 微信开放平台模板消息类
* Class WxModelMessageClass
* (c) 2017 WHB <info@whongbin.cn>, 木木彡博客
*
*/
class WxModelMessageClass {
/**
* 应用唯一标识
* @var string
*/
private $_Appid = '';
/**
* 应用密钥
* @var string
*/
private $_Appsecret = '';
/**
* token
* @var string
*/
private $_Access_token = '';
/**
* 构造函数,获得全局access_token
*/
public function __construct(){
$this->_Appid = $GLOBALS['WX_APPID'];//配置内容,写死也行
$this->_Appsecret = $GLOBALS['WX_APPSECRET'];//配置内容,写死也行
$this->_Access_token = self::getAccessToken();
}
public function getAccessToken()
{
$db = $GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default'];
$con = mysqli_connect($db['host'],$db['user'],$db['password'],$db['dbname']);
if(!$con){
die("connect error:".mysqli_connect_error());
}
//设置字符集
mysqli_set_charset( $con , "utf8" );
//查询access_token
$sql1 = "select * from sys_access_token where uid= 1 ";
$result = $con->query($sql1);
$row = $result->fetch_assoc();
if ($row['expired'] < time()) {
// token已过期
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->_Appid."&secret=".$this->_Appsecret;
$res = json_decode($this->http_request($url),true);
if ($res["errcode"]!=0) echo 'get accesstoken error!';
$access_token = $res['access_token'];
if (isset($access_token)) {
//写数据库
$crdate = time();
$expired = time() + 7000;
$sqlu = "update sys_access_token set token=?,crdate=?,expired=? where uid=1 ";
$stmt = $con->prepare($sqlu);
$stmt->bind_param("sii", $access_token, $crdate,$expired);
$stmt->execute();
$stmt->close();
}
}else{
// token未过期
$access_token = $row['token'];
}
$con->close();
return $access_token;
}
/**
* 发送模板消息
* @param array $data [description]
* @return [type] [description]
*/
public function sendMessage($data=array())
{
if (empty($data) || !is_array($data)) {
throw new Exception('没有请求数据!');
}else{
$token = $this->_Access_token;
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
$res = $this->http_request($url,$data);
return json_decode($res,true);
}
}
/**
* [http_request description]
* @param [type] $url [description]
* @param [type] $param [description]
* @return [type] [description]
*/
public function http_request($url, $param=array()){
$httph =curl_init($url);
curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($httph,CURLOPT_RETURNTRANSFER,1);
curl_setopt($httph, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
curl_setopt($httph, CURLOPT_POST, 1);//设置为POST方式
curl_setopt($httph, CURLOPT_POSTFIELDS, json_encode($param,true));
curl_setopt($httph, CURLOPT_RETURNTRANSFER,1);
curl_setopt($httph, CURLOPT_HEADER,FALSE);
$rst=curl_exec($httph);
curl_close($httph);
return $rst;
}
}
使用示例
/**
* [发送微信模板消息 description]
* @return [type] [description]
*/
public function sendWxModelMessage()
{
$wxModel = new \Whb\Weixin\WxModelMessageClass();
$date = array();
$date['openid'] = '即将要发送给的微信用户';
$date['modelid'] = '微信公众平台获取的模板id';
$date['url'] = 'http://www/yoursite.com/index.php?id=146';
$date['first'] = '通知标题' ;
$date['keyword1'] = 'keyword1';
$date['keyword2'] = 'keyword2';
$date['keyword3'] = 'keyword3';
$date['keyword4'] = 'keyword4';
$date['keyword5'] = 'keyword5';
$date['remark'] = '补充说明';
$template = $this->templateMessage($date);
$res = $wxModel->sendMessage($template);
return $res;
}
/**
* 构造模板消息(审核通过)
* {{first.DATA}}
* 活动名称:{{keyword1.DATA}}
* 开奖时间:{{keyword2.DATA}}
* 中奖号码:{{keyword3.DATA}}
* 奖品名称:{{keyword4.DATA}}
* 奖品金额:{{keyword5.DATA}}
* {{remark.DATA}}
*
* @param [type] $date [description]
* @return [type] [description]
*/
public function templateMessage($date)
{
$template_data = array(
'touser' => $date['openid'],
'template_id' => $date['modelid'],
'url' => $date['url'],
'data' => array(
'first' => array(
'value' => $date['title'],
'color' => '#743A3A'
),
'keyword1' => array(
'value' => $date['actname'],
'color' => '#0000FF'
),
'keyword2' => array(
'value' => $date['time'],
'color' => '#0000FF'
),
'keyword3' => array(
'value' => $date['drawnum'],
'color' => '#0000FF'
),
'keyword4' => array(
'value' => $date['prizename'],
'color' => '#0000FF'
),
'keyword5' => array(
'value' => $date['prizeval'],
'color' => '#0000FF'
),
'remark' => array(
'value' => $date['remark'],
'color' => '#008000'
)
)
);
return $template_data;
}
再说一句
虽然说微信的文档坑是不少,但是细心去看的话还是会少走很多弯路的[aru_36]
网友评论