<?php
namespace app\api\controller;
use think\Controller;
use think\Request;
class Send extends Controller
{
protected $appid;
protected $appSecret;
public function __construct(Request $request = null)
{
parent::__construct($request);
$this->appid = 'xxxxxx';
$this->appSecret = 'xxxxxxxxxxxx';
}
// 发送 POST 请求的函数
function send_post($url, $post_data){
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type:application/json',
'content' => $post_data,
'timeout' => 60
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
return $result;
}
// 小程序 appID 和 appSecret 获取 token
public function getAccessToken($appid,$appsecret){
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $appsecret;
$html = file_get_contents($url);
$output = json_decode($html, true);
$access_token = $output['access_token'];
return $access_token;
}
public function send($open_id,$template_id,$data,$page){
$post_data = array(
// 用户的 openID,可用过 wx.getUserInfo 获取
"touser" => $open_id,
// 小程序后台申添加的订阅消息模板 ID
"template_id" => $template_id,
// 点击模板消息后跳转到的页面,可以传递参数
"page" => $page,
// 发送给用户的数据
"data" => $data
);
file_put_contents('dingyue2.txt',date('Y-m-d H:i:s').json_encode($post_data, true).PHP_EOL, FILE_APPEND);
$appid=$this->appid;
$appsecret=$this->appSecret;
// // 这里替换为你的 appID 和 appSecret
$url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$this->getAccessToken($appid,$appsecret);
$data = json_encode($post_data, true);
$return = $this->send_post($url, $data);
file_put_contents('dingyue.txt',date('Y-m-d H:i:s').json_encode($return, true).PHP_EOL, FILE_APPEND);
}
}
然后就是调用这个发送消息的方法
$send = new Send();
$data = [
'character_string1'=>['value'=>$order['order_id']],//订单编号
'thing8'=> ['value'=>$goodsName['name']],//订单商品名称
'amount3'=>['value'=>$insert['price'].'元'],//支付金额
'time2'=>['value'=>date('Y-m-d h:i:s')]//下单时间
];
$page = 'pages/mine/orderList?index';
$result = $send->send($open_id,'fhxMhOKZuf_uw_VnfketbtmXgWkd3OX3kmMqKKxZkqU',$data,$page);
|