<?php
namespace app\common\controller;
use app\common\library\Auth;
use think\Config;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Hook;
use think\Lang;
use think\Loader;
use think\Request;
use think\Response;
use think\Route;
use think\Session;
/**
* API控制器基类
*/
class Message
{
/**
* 发送模板消息
*/
public function send_notice($openid,$data){
//获取access_token
if (Session::get('access_token')){
$access_token2=Session::get('access_token');
}else{
$pub = \addons\epay\library\Service::getConfig();
$appid = $pub['app_id'];//商户账号appid
$secret = $pub['app_secret'];//
$json_token=$this->curl_post("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "");
$access_token1=json_decode($json_token,true);
$access_token2=$access_token1['access_token'];
Session::set('access_token',$access_token2,7200);
}
//模板消息
$json_template = $this->json_tempalte($openid,$data);
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token2;
$res=$this->curl_post($url,urldecode($json_template));
$res=explode(',', $res);
if ($res[0]==0){
return '发送成功';
}else{
return '发送失败';
}
}
/**
* 将模板消息json格式化
*/
public function json_tempalte($openid,$data){
//模板消息
$template=array(
'touser'=>$openid, //用户openid
'template_id'=>$data['tenpalate_id'], //在公众号下配置的模板id
'url'=>$data['url'], //点击模板消息会跳转的链接
'topcolor'=>"",
'data'=>array(
'first'=>array('value'=>urlencode($data['memo']),'color'=>"#333"),
'keyword1'=>array('value'=>urlencode($data['title']),'color'=>'#333'), //keyword需要与配置的模板消息对应
'keyword2'=>array('value'=>urlencode($data['news']),'color'=>'#333'),
'keyword3'=>array('value'=>urlencode($data['k3']),'color'=>'#333'),
'remark' =>array('value'=>urlencode($data['remark']),'color'=>'#333'), )
);
$json_template=json_encode($template);
return $json_template;
}
/**
* @param $url
* @param array $data
* @return mixed
* curl请求
*/
function curl_post($url , $data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// POST数据
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
调用此方法
$data = [
'tenpalate_id' => "OMNh_zHf0Z2KrmLSKujZbwM2FsECRAGP2dIxV03ZbaM",
"url" => 'http://wx.baicu.com',
"title" => $res['product_title'],
"news" => date("Y-m-d",$res['data_time'])." ".$res['departuretime'],
"k3" => $res['departure'],
"memo"=>'您好,您有一个旅游团将出发。',
"remark" => '详情请查看个人中心。',
];
$openid = "oSG9ew7_rWVV3ZxyyH_KQ4BRrA2A";//'oSG9ew7_rWVV3ZxyyH_KQ4BRrA2A';
$message = new \app\common\controller\Message();
$message->send_notice($openid, $data);