php实现微信小程序消息通知

结合着文档,一天忙下来,小程序的消息通知可以跑通了

 

接入消息通知指引地址:https://mp.weixin.qq.com/debug/wxadoc/dev/api/custommsg/callback_help.html

文档地址:https://mp.weixin.qq.com/debug/wxadoc/dev/api/notice.html#%E6%A8%A1%E7%89%88%E6%B6%88%E6%81%AF%E7%AE%A1%E7%90%86

看完这两个地址基本上你就明白是怎么实现消息通知的了,下面就是需要根据自己的业务需求写php代码了

php中业务分为以下几个步骤:

1、小程序后台消息模板设置获取模板ID

2、微信公众平台|小程序->设置->开发设置 获取AppID(小程序ID)、AppSecret(小程序密钥   注:重置后导致之前的失效)

3、通过AppID、AppSecret调用接口生成ACCESS_TOKEN

4、获取form_id

5、发送模板消息

 

下面是实现上面步骤的详细过程:

一、获取模板ID

二: 获取AppID(小程序ID)、AppSecret(小程序密钥   注:重置后导致之前的失效)

三、生成ACCESS_TOKEN

接口地址:

https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET


代码实现:

public function getAccessToken(Request $r)
{
$appId = Input::get('appId',NULL);
$appSecret = Input::get('appSecret',NULL);

$r = file_get_contents("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret"); //返回的是字符串,需要用json_decode转换成数组
$data = json_decode($r,true);

return $data['access_token'];

}

四、获取form_id

需要在小程序上做个form表单提交,可以前端生成传到后台,就可以获取到了

注:
页面的 <form/> 组件,属性report-submit为true时,可以声明为需发模板消息,此时点击按钮提交表单可以获取formId,用于发送模板消息(多个地方生成form_id传给后端)。
form_id的长度:Android是13位时间戳、iOS是32位GUID
form_id其实就是前端负责获取,传给后端,后端将form_id存起来,在业务中用到消息通知的时候从表里面取出来

form_id中需要注意的一点:一个form_id只能用一次,所以在建表的时候需要给个status区分已使用和未使用的状态(这个坑已经进去过,发送完模板不修改status值,会使得消息通知偶尔成功,偶尔失败)


五、发送模板消息

上面需要的参数都准备好了,OK,这里自己封装了一个方法。然后在用到的地方调用的
封装的方法如下:
public function sendMessage()
{
$token = $this->getToken();
$post = [];
$post['touser'] = '用户openId';
$post['page'] = 'index';
$post['emphasis_keyword'] = 'keyword1.DATA';
$post['color'] = '#173177';

$post['template_id'] = '模板id';
$post['form_id'] = 'formId';
$post['data'] = [
'keyword1'=>['value'=>'xxxxxx','color'=>'#173177'],
'keyword2'=>['value'=>'2018-03-06 14:22:34','color'=>'#173177'],
'keyword3'=>['value'=>'xxxxxx','color'=>'#173177']
];

$url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$token;
$re = $this->curl_url($url,$post);
return $re;
}

private function curl_url($url, $json)
{
$body = json_encode($json);
$headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);

return $result;

}

调用:
public function send(Request $r)
{
$wechat = new WeChatApi();
$re = $wechat->sendMessage();
return $re;

}



到这里就可以实现消息通知了



 

 

 

 

posted @ 2018-03-07 11:02  养成记  阅读(5744)  评论(0编辑  收藏  举报