第一步:申请公众号测试接口
第二步:添加测试用户

第三步:添加消息模板

代码:获取动态ACCESS_TOKEN (有效期7200)
$appid='wxcfd6d103e4d5b35d';
$secret='60504239fe7597a9653b6272ae149369';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
$token = getJson($url);
$access = $token["access_token"];
print_r($token);
print_r("\n");
发送模板消息
一定要注意json格式 ,否则会返回POST数据格式不正确
$url ="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access;
$data1 = '{
"touser":"o4f0Wv5nRBQMCzZ1AsDlq_9OsOrU",
"template_id":"HMnswJkdFHz_ZcINVzpuYE88PGMH20j4Rybr9BVfcjA",
"url":"http://www.rainfly.cn",
"data":{"frist":{"value":"提醒事件已经到了!","color":"#ff0000"}}
}';
function send_post($url, $post_data) {
$postdata = http_build_query($post_data);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/x-www-form-urlencoded',
'content' => $post_data,
'timeout' => 15 * 60 // 超时时间(单位:s)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
//file_put_contents('access.json', $result);
//print_r($result);
//return $result;
}
send_post($url, $data1);
测试截图


评论一下?