微信公众号发送模板消息
附上微信公众平台文档链接:https://mp.weixin.qq.com/debug/cgi-bin/readtmpl?t=tmplmsg/faq_tmpl
实现思路:
1.在公众平台配置好参数(授权地址、授权回调地址、模板消息模板 。三者缺一不可)
2.获取access_token https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html
3.拼装数据格式
4.调用发送接口https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
public function sendPasswordMsg($data)
{
$password = isset($data['password']) ? $data['password'] : '';
$admin_id = isset($data['admin_id']) ? $data['admin_id'] : '';
$computer_room_name = isset($data['computer_room_name']) ? $data['computer_room_name'] : '机房东(西)门锁';
if(empty($admin_id))
{
$this->addErr('929196');
return false;
}
if(empty($password))
{
$this->addErr('929363');
return false;
}
//获取用户openid
$user_info = json_decode($this->callApi('admin/batGetName', ['admin_ids' => $admin_id]), true)['data']['batGetName'][0];
$msg_temp_data = [];
//数据格式需要根据你们的业务自己变动,我的和你们的不一样,和官网的也不一样
$msg_temp_data['data'] = json_encode(['first' => " 你好!\r\n", 'keyword1' => $computer_room_name . "\r\n", 'keyword2' => $password."\r\n", 'remark' => '请在有效时间内使用']);
$msg_temp_data['openid'] = $user_info['openid'];
$msg_temp_data['template_id'] = C('DOOR_PWD_TMP_MSG_CODE');
$access_token = getWechatAccessToken();
$template_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;
//发送模板消息
$result = post($template_url, json_encode($msg_temp_data));
// $result = json_decode($this->callApi('msg/sendTempMsg', $msg_temp_data), true)['data'];
$this->addData(__FUNCTION__, $result ? $result : 0);
}