小程序发送服务通知
<?php/***小程序发送服务通知*这里只做单纯的功能测试,没有涉及任何业务逻辑1 前台传post参数code(用户身份临时凭证)和formid(表单提交场景submit事件带上的formId,支付场景没有测试)2 通过code获取openid3 获取接口调用凭证access_token,调用发消息模板接口需要用到4 获取模板id,组装消息数据,调用发消息接口发送官方文档地址:https://developers.weixin.qq.com/miniprogram/dev/api/notice.html#%E4%BD%BF%E7%94%A8%E8%AF%B4%E6%98%8E*///获取openidfunction getOpenid(){ $appid='wxd204fed0cf926fe6'; $appsecret='4e77e491b757dbadbfcc94652d42c0f4'; $code=$_POST['code']; $url="https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code"; $request=file_get_contents($url); return json_decode($request)->openid;}//获取接口调用凭证access_token function getAccessToken(){ $appid='wxd204fed0cf926fe6'; $secret='4e77e491b757dbadbfcc94652d42c0f4'; $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret"; $access_token = file_get_contents($url); return json_decode($access_token)->access_token;}//发送模板消息function sendMsg($data,$access_token){//这个方法里面的代码来源于百度复制,能否用于生产有待考究 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$access_token); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_AUTOREFERER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $tmpInfo = curl_exec($ch); if (curl_errno($ch)) { return curl_error($ch); }
curl_close($ch); return $tmpInfo;}//formid$formid=$_POST['formid'];//获取openid$openid=getOpenid();//获取access_token$access_token=getAccessToken();//模板数据,微信要的是json数据,我这里先构建数组再转成json$data=array( 'touser'=>''.$openid,//要发送的用户 'template_id'=>'w0oU8HEJL3uuwxB5zYEcWpnRkOYuKjN9zzIwu7nQVz8',//模板id,从模板库中获取,可通过接口获取或直接从小程序后台复制 "page"=>"index",//跳转小程序的页面 'form_id'=>''.$formid,//表单提交场景下,为 submit 事件带上的 formId;支付场景下,为本次支付的 prepay_id 'data'=>array( 'keyword1'=>array( 'value'=>'产品名称', ), 'keyword2'=>array( 'value'=>'订单号', ), 'keyword3'=>array( 'value'=>'订单价格', ), 'keyword4'=>array( 'value'=>'订购时间', ),
), 'emphasis_keyword'=>'keyword1.DATA' //需要放大显示的关键词 );//发送模板消息$result=sendMsg(json_encode($data),$access_token);var_dump($result);?>
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。

