laravel框架 微信模板消息发送
/**
* 发送模板消息
*/
public function add(Request $request,$id){
$house_data = House::find($id);
$phone = $request->input('phone','');
$template=array(
'touser'=>'', //接收消息模版用户的openid
'template_id'=>"", //在公众号下配置的模板id
'url'=>"", //点击模板消息会跳转的链接
'topcolor'=>"#7B68EE",
'data'=>array(
//'first'=>array('value'=>urlencode("微信模版消息发送测试"),'color'=>"#FF0000"),
'keyword1'=>array('value'=>$house_data->title,'color'=>'#FF0000'), //keyword需要与配置的模板消息对应
'keyword2'=>array('value'=>$request->btn,'color'=>'#FF0000'),
'keyword3'=>array('value'=>$house_data->site,'color'=>'#FF0000')
)
);
$token = session("access_token_mp");
if($token){
return $token;
}
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=你的aphid&secret=公众号的secret";
$res = $this->curl_post($url);
$td = json_decode($res, true);
if($td['access_token']){
$access_token = session("access_token_mp", $td['access_token'], $td['expires_in'] - 120);//获取微信公众平台token
session(['weixin_token'=>$access_token]);
$json_template=json_encode($template);
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
$res=$this->curl_post($url,urldecode($json_template));
// dd($res);
echo '<script>alert("微信模版消息发送成功");location="'.$_SERVER['HTTP_REFERER'].'"</script>';
// return $td['access_token'];
}else{
return false;
}
exit;
}
下面展示一些 内联代码片
。
/**
* @param $url
* @param array $data
* @return mixed
* curl请求
*/
function curl_post($url , $data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// POST数据
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}