信息整合
$msg = [
'thing3' => ['value'=> '邀请好友购课奖励积分'],
'thing1' => ['value'=> $data3['integral']],
'thing2' => ['value'=> $welfare],
'date4' => ['value'=> date('Y-m-d H:i:s', time())],
];
//订阅格式请参照小程序订阅消息模板中的格式
发起消息接口
/***
* 订阅消息模板
* @param $touser //需要接受订阅消息的openid
* @param $template_id //模板ID
* @param $page //点击返回页面路径
* @param $dataArray //订阅格式请参照小程序订阅消息模板中的格式
* @return array
*/
public function sendSubscribeMessage($touser, $template_id, $page, $dataArray)
{
//access_token 一般都存在缓存 ,
$access_token = $this->get_access_token();
//请求url
$url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token ;
//发送内容
$data = [] ;
$data['touser'] = $touser; //用户的openid
$data['template_id'] = $template_id; //所需下发的订阅模板id
//点击模板卡片后的跳转页面,仅限本小程序内的页面。支持带参数,(示例index?foo=bar)。该字段不填则模板无跳转。
$data['page'] = $page;
//模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
$data['data'] = $dataArray;
//跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
$data['miniprogram_state'] = 'formal';
$data['lang'] = 'zh_CN';
$json_data = json_encode($data);
return [
'openid' => $touser,
'data' => $this->curlRequest($url, $json_data)//这里面就是个curl请求 , 转成数组返回
];
}
获取微信AccessToken
/**
* 微信小程序获取接口调用凭证AccessToken
*/
public function get_access_token1()
{
$config = Db::name('cycling_config')->where('id',1)->field('wechat_appid,wechat_appsecret')->find();
$APPID = $config['wechat_appid'];// 小程序appid
$APPSECRET = $config['wechat_appsecret']; // 小程序appsecret
//获取access_token
$access_token ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
//缓存access_token
session_start();
$_SESSION['access_token'] ="";
$_SESSION['expires_in'] = 0;
$ACCESS_TOKEN ="";
if(!isset($_SESSION['access_token']) || (isset($_SESSION['expires_in']) && time() >$_SESSION['expires_in']))
{
$json = $this->httpRequest($access_token );
$json = json_decode($json,true);
if(empty($json['access_token'])){
$this->result('', 0, $json['errmsg']);
}
$_SESSION['access_token'] =$json['access_token'];
$_SESSION['expires_in'] = time()+7200;
$ACCESS_TOKEN =$json["access_token"];
}
else{
$ACCESS_TOKEN = $_SESSION["access_token"];
}
return $ACCESS_TOKEN;
}
发起请求
/**
* @param string $url post请求地址
* @param array $params
*/
function curlRequest($url, $params)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt(
$ch, CURLOPT_HTTPHEADER,
array(
'Content-Type: application/json'
)
);
$data = curl_exec($ch);
curl_close($ch);
return ($data);
}