** PHP:微信公众号–发送模板信息**
微信post 示例如下:
其实url 和 miniprogram 可以不写 看需求
url:相当于详情页面
请注意,URL置空,则在发送后,点击模版消息会进入一个空白页面(ios),或无法点击(android)。
{
"touser":"OPENID",
"template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
"url":"http://weixin.qq.com/download",
"miniprogram":{
"appid":"xiaochengxuappid12345",
"pagepath":"index?foo=bar"
},
"data":{
"first": {
"value":"恭喜你购买成功!",
"color":"#173177"
},
"keyword1":{
"value":"巧克力",
"color":"#173177"
},
"keyword2": {
"value":"39.8元",
"color":"#173177"
},
"keyword3": {
"value":"2014年9月22日",
"color":"#173177"
},
"remark":{
"value":"欢迎再次购买!",
"color":"#173177"
}
}
}
- 获取 Token
//获取access_token
$TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$json=file_get_contents($TOKEN_URL);
$result=json_decode($json,true);
$ACCESS_TOKEN=$result['access_token'];
-
组合post数据
这些键 名怎么取的 :
模板ID 详情信息
$template = array(
'touser'=>$openid,//OpenId
'template_id'=>$template_id,//模板信息ID
'topcolor'=>'#FF0000',
'data'=>array(
'template_id' => array(
'value' => $template_id,//模板信息ID
'color' => '#FF0000'
),
'first' => array(
'value' => "", //随便写点什么吧
'color' => '#008B8B'
),
'keyword1' => array(
'value' => "", //随便写点什么吧
'color' => '#2F4F4F'
),
'keyword2' => array(
'value' => "", //随便写点什么吧
'color' => '#00CED1'
),
'keyword3' => array(
'value' => "",
'color' => '#FF0000'
),
'keyword4' => array(
'value' => "",
'color' => '#1E90FF'
),
'keyword5' => array(
'value' => "",
'color' => '#00BFFF'
),
)
);
- 发送模板信息 - 请求微信接口
//access_token改成你的有效值
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=". $ACCESS_TOKEN;
$json = json_encode($template);
$fanhui = do_post_request($url,$json);
$result=json_decode($fanhui,true);
- do_post_request 方法
//post函数
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url");
}
return $response;
}