首先准备一个测试公众号
获取access_token
要设置ip白名单
创建推送测试信息模板 正式上面需要在模板库中选择
然后直接上代码了
$APPID = '';
$AppSecret = '';
$action = $_GET['action'] ? $_GET['action'] : '';
switch ($action) {
case 'tui':
$res = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $APPID . "&secret=" . $AppSecret . "");
$res = json_decode($res, true);
$access_token = $res['access_token'];
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
$toopenid = "oGMZp0i9VZIvInuHGgISrk9Cn8mo";
$params = [
'touser' => $toopenid,
"template_id" => "cgTold1JM7nUEWKwfvSQUPUE_pCDJ4MXt2YGB-DJ1Tg",
"url" => "点开通知 要打开的链接地址",
"data" => [
"first" => [
"value" => "1111",
"color" => "#173177"
],
"keyword1" => [
"value" => "企业认证",
"color" => "#173177"
],
"keyword2" => [
"value" => "通过",
"color" => "#173177"
],
]
];
$messagedata = json_encode($params, JSON_UNESCAPED_UNICODE);
//发送微信模板
$data = http_post($url, $messagedata);
print_r($data);die;//{"errcode":0,"errmsg":"ok","msgid":1348094199752916996}
break;
default:
# code...
break;
}
function http_post($remote_server, $post_string) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remote_server);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ssl = substr($remote_server, 0, 8) == "https://" ? TRUE : FALSE;
if ($ssl)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
本地执行地址
然后
{“errcode”:0,“errmsg”:“ok”,“msgid”:1348094199752916996}
出现其他错误可以查看下面文档
https://mp.weixin.qq.com/debug/cgi-bin/readtmpl?t=tmplmsg/faq_tmpl