前言
小程序推送限制性较强,用户活跃度低几乎就无法推送,如张小龙设计的那般,用完就走(该接口将于2020/01/10下线,详见新的订阅消息文章)
代码
<?php
class PushService
{
protected $touser;
protected $template_id;
protected $page;
protected $form_id;
protected $data;
protected $emphasis_keyword;
public function __construct($userOpenid, $formId, $page, $data, $emphasisKeyword = '')
{
$this->touser = $userOpenid;
$this->page = $page;
$this->form_id = $formId
$this->data = $this->paramsDeal($data);
$this->emphasis_keyword = $emphasisKeyword;
}
/**
* 通知
*/
public function someMsg($tmpId){
$this->template_id = $tmpId;
return $this->doPush();
}
/**
* 发送推送
* @return bool|mixed
*/
public function doPush(){
if(!$this->form_id){
return false;
}
$pushData = [
'touser' => $this->touser,
'template_id' => $this->template_id,
'page' => $this->page,
'form_id' => $this->form_id,
'data' => $this->data,
];
if($this->emphasis_keyword){
$pushData['emphasis_keyword'] = $this->emphasis_keyword;
}
$wx = new WeiXinService();
$result = $wx->pushToUser(json_encode($pushData));
return $result;
}
/**
* 处理模版内容
* @param $data
* @return array
*/
public function paramsDeal($data){
$i = 1;
$result = [];
foreach ($data as $v){
$result['keyword'.$i] = array(
'value' => $v
);
$i++;
}
return $result;
}
}
<?php
class WeiXinService
{
/**
* @var String appID 微信小程序AppID
*/
protected $appID;
/**
* @var String AppSecret 微信小程序AppSecret
*/
protected $appSecret;
public function __construct()
{
$this->appID = $this->config['appID'];
$this->appSecret = $this->config['appSecret'];
}
/**
* 获取accessToken
*/
public function getAccessToken(){
$hashKey = md5($this->appID);
$access_token = UtilCache::getCache($hashKey);
if($access_token){
return $access_token;
}
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appID."&secret=".$this->appSecret;
$result = json_decode(NnCommon::curlPost($url, []), true);
if(!$result['access_token']){
return '';
}
UtilCache::setCache($hashKey, $result['access_token'], 7000);
return $result['access_token'];
}
/**
* 小程序消息推送
* @param $data
* @return mixed
*/
public function pushToUser($data){
$url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=".$this->getAccessToken();
$res = json_decode(NnCommon::curlPost($url, $data, 1), true);
return $res;
}
}
$params = [];
$push = new PushService(****);
$res = push->someMsg($tplId);
