/**
*小程序 发送模板消息
*/
public function send_template_news()
{
$form_id = ''; //form_id 有两种 一种为提交过表单后生成的form_id 一种为支付后生成的prepay_id
$template_id = ''; //小程序后台设置的模板id
$openid = '' ; //用户的openid
$access_token = $this->get_access_token(); //access_token
$url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=$access_token";
$data = [
//此处数据对应与小程序后台设置的模板结构
"keyword1" => ["value" => $order_no],//订单号
"keyword3" => ["value" => $payment_money],//支付金额
"keyword4" => ["value" => date('Y-m-d H:i:s',$create_time)],//支付时间
];
$post = [
"touser" => $openid,
"template_id" => $template_id,
"page" => "pages/index/index", //点击
"form_id" => $prepay_id,
"data" => $data,
];
$this->http($url, json_encode($post));
}
获取access_token
public function get_access_token()
{
if (cache('access_token')){ //此处为tp5cache缓存
$access_token = cache('access_token');
}else{
$WX_APPID = ''; //小程序appid
$WX_SECRET = ''; //小程序appsecret
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$WX_APPID.'&secret='.$WX_SECRET;
$infos = json_decode(file_get_contents($url));
$access_token = $infos->access_token;
cache('access_token',$access_token,7000);
}
return $access_token;
}
发送http请求
/** Get 或 Post 请求
* @param $url
* @param null $data 为null时,为post方法
* @return mixed
*/
public function http($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
if (!empty($data)) {
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}