//微信官方的data格式
{
"touser":"OPENID",
"template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
"url":"http://weixin.qq.com/download",
"topcolor":"#FF0000",
"data":{
"first": {
"value":"嘤嘤嘤",
"color":"#173177"
},
"keyword1":{
"value":"咯咯咯",
"color":"#173177"
},
"remark":{
"value":"0426",
"color":"#173177"
}
}
}
//因为有时候会出现data为空什么的错误
//数组的方式倒是能成功
public function sendmuban($openid,$content) {
$access_token = $this->getAccessToken();
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=$access_token";
$template = array(
'touser'=>$openid,
'template_id'=>"1ZvtiA8FSJbCocySmVgpJk4qCtN6sLpkpL2gJUtApXU",
'url'=>"http://www.baidu.com",
'data'=>array(
'first'=>array(
'value'=>urlencode($content),
'color'=>"#173177",
),
'keyword1'=>array(
'value'=>urlencode($content),
'color'=>"#173177",
),
'remark'=>array(
'value'=>urlencode("咯咯咯"),
'color'=>"#173177",
)
)
);
$data = urldecode(json_encode($template));
$result = $this->http_request($url,$data);
return json_decode($result,true);
}
//获取公众号全局Access Token
function getAccessToken() {
$tokenFile = "./access_token123.json";
$data = json_decode(file_get_contents($tokenFile));
if ($data->expire_time < time() || !$data->expire_time) {
$appid = C('MPCONFIG.APPID');
$secret = C('MPCONFIG.APPSECRET');
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
$result = json_decode($this->http_request($url),true);//var_dump($result);die;
$access_token = $result['access_token'];
if($access_token) {
$data_new['expire_time'] = time() + 7000;
$data_new['access_token'] = $access_token;
file_put_contents($tokenFile, json_encode($data_new));
}
}else{
$access_token = $data->access_token;
}
return ($access_token);
}
function http_request($url, $data = null){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
网友评论