|
|
<?php
|
|
|
namespace LaneWeChat\Core;
|
|
|
|
|
|
/**
|
|
|
* 模板消息接口
|
|
|
* 此类提供了微信公众号模板消息的相关操作,包括设置行业、获取模板ID和发送模板消息。
|
|
|
* 模板消息用于公众号向用户发送重要的服务通知,如信用卡刷卡通知、商品购买成功通知等。
|
|
|
* 不支持广告等营销类消息以及其它所有可能对用户造成骚扰的消息。
|
|
|
*/
|
|
|
class TemplateMessage {
|
|
|
|
|
|
/**
|
|
|
* 设置所属行业
|
|
|
* 公众号模板消息需要设置所属行业,每月可更改1次所选行业。
|
|
|
* @param int $industryId1 公众号模板消息所属行业编号,第一个行业编号
|
|
|
* @param int $industryId2 公众号模板消息所属行业编号,第二个行业编号
|
|
|
* @return mixed 返回调用结果,通常是一个数组或者JSON字符串
|
|
|
*/
|
|
|
public static function setIndustry($industryId1, $industryId2) {
|
|
|
// 构建请求URL,包含access_token
|
|
|
$queryUrl = 'https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=' . AccessToken::getAccessToken();
|
|
|
// 设置请求方法为POST
|
|
|
$queryAction = 'POST';
|
|
|
// 构建请求数据数组
|
|
|
$template = array();
|
|
|
$template['industry_id1'] = "$industryId1";
|
|
|
$template['industry_id2'] = "$industryId2";
|
|
|
// 将数组转换为JSON格式
|
|
|
$template = json_encode($template);
|
|
|
// 调用Curl类发送请求
|
|
|
return Curl::callWebServer($queryUrl, $template, $queryAction);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 获得模板ID
|
|
|
* 从模板库中添加模板,获取模板ID。
|
|
|
* @param string $templateIdShort 模板库中模板的编号,有“TM**”和“OPENTMTM**”等形式
|
|
|
* @return mixed 返回调用结果,通常是一个数组或者JSON字符串
|
|
|
*/
|
|
|
public static function getTemplateId($templateIdShort) {
|
|
|
// 构建请求URL,包含access_token
|
|
|
$queryUrl = 'https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=' . AccessToken::getAccessToken();
|
|
|
// 设置请求方法为POST
|
|
|
$queryAction = 'POST';
|
|
|
// 构建请求数据数组
|
|
|
$template = array();
|
|
|
$template['template_id_short'] = "$templateIdShort";
|
|
|
// 将数组转换为JSON格式
|
|
|
$template = json_encode($template);
|
|
|
// 调用Curl类发送请求
|
|
|
return Curl::callWebServer($queryUrl, $template, $queryAction);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 向用户推送模板消息
|
|
|
* 发送模板消息给指定的用户。
|
|
|
* @param array $data 模板数据,包含多个键值对,每个键对应模板中的一个参数
|
|
|
* @param string $touser 接收方的OpenId
|
|
|
* @param string $templateId 模板Id,在公众平台线上模板库中选用模板获得ID
|
|
|
* @param string $url 点击模板消息会跳转到的链接
|
|
|
* @param string $topcolor 顶部颜色,可以为空,默认是红色
|
|
|
* @return mixed 返回调用结果,通常是一个数组或者JSON字符串
|
|
|
*/
|
|
|
public static function sendTemplateMessage($data, $touser, $templateId, $url, $topcolor = '#FF0000') {
|
|
|
// 构建请求URL,包含access_token
|
|
|
$queryUrl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . AccessToken::getAccessToken();
|
|
|
// 设置请求方法为POST
|
|
|
$queryAction = 'POST';
|
|
|
// 构建请求数据数组
|
|
|
$template = array();
|
|
|
$template['touser'] = $touser;
|
|
|
$template['template_id'] = $templateId;
|
|
|
$template['url'] = $url;
|
|
|
$template['topcolor'] = $topcolor;
|
|
|
$template['data'] = $data;
|
|
|
// 将数组转换为JSON格式
|
|
|
$template = json_encode($template);
|
|
|
// 调用Curl类发送请求
|
|
|
return Curl::callWebServer($queryUrl, $template, $queryAction);
|
|
|
}
|
|
|
} |