1 登录微信公众平台 : https://mp.weixin.qq.com/ , 左侧模板消息。从模板库选择你所需要的模板,获取模板ID
2 列表最右侧,进入 详情,可以看到 请求的参数格式信息。PHP封装时候data 数据要严格按照这个格式来操作
3 代码实现: 访问以下代码的 test方法 即可进行测试 (以下代码经过我亲测,可用)
<?php
// +----------------------------------------------------------------------
// | Todo: 模板消息发送
// +----------------------------------------------------------------------
// | Author: 依然范儿特西 : richerdyoung@foxmail.com
// +----------------------------------------------------------------------
namespace Wechat\Controller;
use Wechat\Controller\WechatController;
class PushController extends WechatController {
/**
* 发送post请求
* @param string $url
* @param string $param
* @return bool|mixed
*/
function request_post($url = ‘‘, $param = ‘‘)
{
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
$data = curl_exec($ch); //运行curl
curl_close($ch);
return $data;
}
/**
* 发送get请求
* @param string $url
* @return bool|mixed
*/
function request_get($url = ‘‘)
{
if (empty($url)) {
return false;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
/**
* @param $appid
* @param $appsecret
* @return mixed
* 获取token
*/
public function get_token(){
$appid = ‘‘;
$secret = "";
$url2 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
$result = json_decode(file_get_contents($url2),true);
$access_token = $result[‘access_token‘];
return $access_token;
}
public function test(){
//openid
$touser = $user_mes[‘wx_openid‘];
//获取token
$access_token = $this->get_token();
//模板ID
$template_id = ‘‘;
$url = "www.baidu.com";
$data=array(
‘first‘=>array(‘value‘=>urlencode("恭喜你哦!"),‘color‘=>"#743A3A"),
‘keyword1‘=>array(‘value‘=>‘22‘,‘color‘=>‘#EEEEEE‘),
‘keyword2‘=>array(‘value‘=>‘33‘,‘color‘=>‘#FFFFFF‘),
‘remark‘=>array(‘value‘=>‘33‘,‘color‘=>‘#FFFFFF‘)
);
$res = $this->Send($touser, $template_id, $url, $data, $access_token);
print_r($res);
}
/**
* 发送自定义的模板消息
* @param $touser
* @param $template_id
* @param $url
* @param $data
* @param string $topcolor
* @return bool
*/
public function Send($touser, $template_id, $url, $data, $access_token, $topcolor = ‘#7B68EE‘)
{
$template = array(
‘touser‘ => $touser, //openid
‘template_id‘ => $template_id,
‘url‘ => $url,
‘topcolor‘ => $topcolor,
‘data‘ => $data
);
$json_template = json_encode($template);
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
$dataRes = $this->request_post($url, urldecode($json_template));
if ($dataRes[‘errcode‘] == 0) {
return true;
} else {
return false;
}
}
}