版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/php_lzr/article/details/84991093
话不多说直接上代码 我这里做的小程序的消息推送 小程序绑定的微信服务号 通过服务号的消息模板给小程序和服务号推送消息 欢迎大家的指导意见 这个链接是微信的官方文档可以参阅 就是 错误码有点少了 https://developers.weixin.qq.com/miniprogram/dev/api/sendUniformMessage.html $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret'; $access_token = curl_get($url); $res = json_decode($access_token['access_token']);//这里有错误 大家改下 这里是json串不是数组 $temp = json_encode(getTemp()); //微信小程序 公众号 绑定 统一发送消息 $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token='.$res; $res = json_decode(curl_post($url, $temp), true); print_r($res); function getTemp() { $data = ['恭喜你购买课程包成功!', 123,12343,123, date('Y-m-d H:i:s',time()), "谢谢您的参与"]; $sendArr = array(); $sendArr['touser'] = 'openid' ; $sendArr['mp_template_msg']['appid'] = 'appid'; $sendArr['mp_template_msg']['template_id'] = 'template_id'; $sendArr['mp_template_msg']['url'] = 'url';//公众号 目前没有跳转链接 写死 跳转到网站的m站 $sendArr['mp_template_msg']['miniprogram']['appid'] = 'appid'; $sendArr['mp_template_msg']['miniprogram']['pagepath'] = '';//小程序跳转链接 $sendArr['mp_template_msg']['data'] = addkey($data); return $sendArr; } //数组下标集合 function keys() { return ['keyword1', 'keyword2', 'keyword3', 'keyword4', 'keyword5', 'keyword6', 'keyword7']; } //添加数组下标 function addkey($par) { if(!is_array($par)) return false; $keys = keys(); $arr = []; for($i=0; $len=count($par), $i<$len; $i++) { if($i) { $arr[$keys[$i - 1]] = $par[$i]; }else{ $arr['first'] = $par[$i]; } } if(count($arr) > 1) $arr['remark'] = array_pop($arr); $data = array(); //拼接成符合微信要求的数组 $num = 0; foreach($arr as $key => $val) { $data[$key] = ['value'=>$val, 'color'=>getColor($num)]; $num ++; } return $data; } function getColor($num) { if($num % 2) { return '#743A3A'; }else { return '#FF0000'; } } function curl_get($url, $params = array(), $timeout = 5) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); $file_contents = curl_exec($ch); curl_close($ch); return $file_contents; } function curl_post($url, $filedata) { $curl = curl_init(); if(class_exists('./CURLFile'))//php5.5跟php5.6中的CURLOPT_SAFE_UPLOAD的默认值不同 { curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true); }else { if(defined('CURLOPT_SAFE_UPLOAD')) { // curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false); } } curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); if(!empty($filedata)) { curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $filedata); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($curl); curl_close($curl); return $output; }