首先进行小程序 推送模板的配置
step 1 : 登录小程序 点击右边的开发菜单
step 2 :在点击右边开发设置 下面有一个消息推送 根据相对应的提示完成配置 (配置的url: 启用并设置消息推送配置后,用户发给小程序的消息以及开发者需要的事件推送,都将被微信转发至该服务器地址中)
php 后台的配置代码
function Msg(){
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];
$echostr = $_GET["echostr"];
$token = '配置的token';
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr, SORT_STRING);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );
$tmpStr == $signature? echo $echostr echo false;
}
step 3 : 创建模板消息
点击功能模块下的消息模版 点击添加模版 然后找到项目需要的相对应的模版消息 选择好关键字 然后保存
以上三部 就完成了 模版消息的创建 后面就是消息推送的代码实现过程
首先小程序的xml文件代码中要包含form表单得到form_id 或者是充值的时候获得的支付id prepay_id (form表单 获得form_id的方法就是在 form组件中设置 report-submit = ‘true’ )
// 下面是推送的php后台代码
function SendMsg()
{
$appid = '小程序的appid';
$secret = '小程序的AppSecret';
$userid = '用户的openid';
$form_id = 'form_id'; // 表单提交的form_id
$prepay_id = 'prepay_id'; // 支付时产生的的支付 prepay_id
$template_id = "step 3 中选择模版的 模版id";
// 配置要推送的数据 这里的内容都以时间来展示
$data_arr = [
"keyword1"=>['value'=>date("Y-m-d H:i:s")],
"keyword2"=>['value'=>date("Y-m-d H:i:s")],
];
$post_data = array (
"touser" => $openid, //用户的 openID,可用过 wx.getUserInfo 获取
"template_id" => $template_id, //小程序后台申请到的模板编号
"page" => "/pages/index/index", //点击模板消息后跳转到的页面,可以传递参数
"form_id" => $form_id?:$prepay_id, //第一步里获取到的 formID 或者是支付的id
"data" => $data_arr, // 需要推送的数据
"emphasis_keyword" => "keyword2.DATA" //需要强调的关键字,会加大居中显示
);
// 获得token值
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
$rest = file_get_contents $url );
$rest = json_decode($rest,true);
$accessToken =$rest['access_token'];
// 调用接口 发送消息
$url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$accessToken;
$json_template = json_encode($post_data,true); //将内容json化
$options = [
'http' => [
'method' => 'POST', // 传输方式为post
'header' => 'Content-type:application/json', //header 需要设置为 JSON
'content' => $json_template, // 需要推送的内容
'timeout' => 60//超时时间
]
];
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
}
当表单发生点击的时候 就会产生form_id 拿到了form_id 就可以直接调用上面的那个推送的接口了 调用成功之后微信那边就直接将要推送的内容 发送到方法当中的那个openid 相对应的微信上
当然这个推送也可以直接在小程序的js文件当中 设置好要推送的内容 直接在js文件中 利用wx.request 请求微信api接口 不一定非得需要后台来操作实现