https://blog.csdn.net/lgj199505/article/details/82425425
https://www.cnblogs.com/tingfengqieyu/p/8808866.html
直接上代码:
/**
* 抽奖结果 小程序发送模板消息
*/
public function integral_result(){
$openid = '用户openid';
$form_id = I("post.fomrId");
$template_id = ""; //服务通知模板id
$access_token= $this->getWxAccessToken();
$url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token ;
$value = array(
"keyword1"=>array(
"value"=> 'ceshi',
"color"=>"#4a4a4a"
),
"keyword2"=>array(
"value"=>'test',
"color"=>"#9b9b9b"
),
);
$dd = array();
$dd['touser']=$openid; //接收者openid
$dd['template_id']=$template_id;
$dd['page']=""; //点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
$dd['form_id']=$form_id; //前端接收的formId
$dd['data']=$value; //模板内容,不填则下发空模板
$dd['color']=''; //模板内容字体的颜色,不填默认黑色
$dd['emphasis_keyword']=''; //模板需要放大的关键词,不填则默认无放大
$this->http_curl($url,"post",json_encode($dd));
}
/**
* 获取access_token
*/
public function getWxAccessToken(){
//缓存access_token
if($_SESSION['access_token'] && $_SESSION['access_token_expire_time']>time()){
$rs = $_SESSION['access_token'];
}else{
$appid = '小程序的appid';
$secret = '小程序的secret';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$res = $this->http_curl($url);
$rs = $res['access_token'];
$_SESSION['access_token'] = $rs;
$_SESSION['access_token_expire_time'] = time()+7000;
}
return $rs;
}
/**
* 封装curl
*/
public function http_curl($url, $type = 'get', $arr ='',$res ='json'){
$cl = curl_init();
curl_setopt($cl, CURLOPT_URL, $url);
curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
if($type == 'post'){
curl_setopt($cl, CURLOPT_POST, 1);
curl_setopt($cl, CURLOPT_POSTFIELDS, $arr);
}
$output = curl_exec($cl);
curl_close($cl);
if($res == 'json'){
if( curl_error($cl)){
return curl_error($cl);
}else{
return json_decode($output, true);
}
}
}