当前位置:网站首页>uniapp消息推送(个推-PHP服务端推送)
uniapp消息推送(个推-PHP服务端推送)
2022-06-10 10:00:00 【开发者MK】
<?php
namespace app\service;
use think\facade\Cache;
/** * Class SinglePushService * 个推文档 https://docs.getui.com/getui/server/rest_v2/push/ * @package app\service * 个推 * thinkphp 6 */
class SinglePushService
{
protected $appId = 'xxx'; // 个推 appid
protected $appKey = 'xxx'; // 个推 appKey
protected $appSecret = 'xxx'; // 个推 appSecret
protected $masterSecret = 'xxx'; // 个推 masterSecret
protected $baseUrl = 'https://restapi.getui.com/v2/'; // 个推 base url
protected $pushUrl = '/push/single/cid'; // 个推 url
protected $tokenUrl = '/auth'; // 个推 token url
/** * singlePush * 个推 post请求 * @param string $title // 标题 * @param string $body // 内容 * @param string $payload // 参数 如跳转的url * @param string $cid 用户cid,使用plus.push.getClientInfoAsync函数获取,可在uni官网找到 * @param int $scheduleTime 毫秒 * ps 这些方法是从个推sdk demo剥离出来的,非个推sdk方法 */
public function singlePush($title, $body, $payload, $cid, $scheduleTime)
{
$token = $this->token(); // token 存redis
$url = $this->baseUrl . $this->appId . $this->pushUrl;
$header = ['token: ' . $token];
$intent = "intent:#Intent;scheme=unipush;launchFlags=0x4000000;component=uni.fanglei950E6FC/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title={
$title};S.content={
$body};S.payload={
$payload};end";
$params = [
'request_id' => uniqid(), // 随便一个唯一数
'audience' => [
'cid' => [$cid]
],
'settings' => [
'ttl' => 3600 * 24 * 1000,// 毫秒
'schedule_time' => $scheduleTime // 定时推送时间
],
'push_message' => [
'notification' => [
'title' => $title,
'body' => $body,
'logo' => 'logo.png', // logo name
'logo_url' => 'https:www.xxx.com.logo.png', // logo url
'click_type' => 'intent',
'intent' => $intent,
]
]
];
$rest = self::httpRequest($url, $params, $header, 'POST');
return $rest;
}
/** * token * 获取token */
private function token()
{
$key = 'single_token';
$redis = Cache::store('redis');
$token = $redis->get($key);
if ($token) return $token; // 有就直接返回 token,没有就去请求token
$url = $this->baseUrl . $this->appId . $this->tokenUrl;
$params = [
'sign' => $this->hash(), // sha256
'timestamp' => $this->mTime(), // 毫秒13位时间戳
'appkey' => $this->appKey,
];
$rest = self::httpRequest($url, $params, null, 'POST');
if ($rest['msg'] == 'success') {
$token = $rest['data']['token'];
$expire = $rest['data']['expire_time']; // 毫秒13位时间戳
$substr = substr($expire, 0, 10);
$ttl = bcsub($substr, time()); // 计算过期时间,存入redis
$redis->set($key, $token, $ttl);
return $token;
}
return false;
}
/** * mTime * 毫秒 */
public function mTime()
{
list($mse, $sec) = explode(' ', microtime());
$mtime = (float)sprintf('%.0f', (floatval($mse) + floatval($sec)) * 1000);
return $mtime;
}
/** * hash */
private function hash()
{
$str = $this->appKey . $this->mTime() . $this->masterSecret;
return hash('sha256', $str);
}
/** * @param $url * @param $data * @param $method * @param $headers * request * 发起请求 curl */
private static function request($url, $data, $method, $headers)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERAGENT, 'GeTui RAS2 PHP/1.0');
curl_setopt($curl, CURLOPT_FORBID_REUSE, 0);
curl_setopt($curl, CURLOPT_FRESH_CONNECT, 0);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, 60000);
curl_setopt($curl, CURLOPT_TIMEOUT_MS, 30000);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$header = null;
if ($headers != null) {
array_push($headers, "Content-Type:application/json;charset=UTF-8", "Connection: Keep-Alive");
$header = $headers;
} else {
$header = array("Content-Type:application/json;charset=UTF-8", "Connection: Keep-Alive");
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
switch ($method) {
case 'GET':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
break;
case 'POST':
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case 'PUT':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); //设置请求方式
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
}
$curl_version = curl_version();
if ($curl_version['version_number'] >= 462850) {
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT_MS, 30000);
curl_setopt($curl, CURLOPT_NOSIGNAL, 1);
}
//请求失败有3次重试机会
$result = self::exeBySetTimes(3, $curl);
return $result;
}
/** * @param $url * @param $params * @param $headers * @param $method * httpRequest * 个推 */
public static function httpRequest($url, $params, $headers, $method)
{
$data = json_encode($params);
$result = null;
try {
$resp = self::request($url, $data, $method, $headers);
$result = json_decode($resp, true);
return $result;
} catch (\Exception $e) {
return $e->getMessage();
}
}
/** * @param int $count 重试次数 * @param $curl * exeBySetTimes * 重试 */
private static function exeBySetTimes($count, $curl)
{
$result = curl_exec($curl);
$info = curl_getinfo($curl);
$code = $info["http_code"];
if (curl_errno($curl) != 0 && $code != 200) {
$count--;
if ($count > 0) {
$result = self::exeBySetTimes($count, $curl);
} else {
if ($code == 0 || $code == 404 || $code == 504) {
return false;
}
}
}
return $result;
}
}
边栏推荐
- 协程asyncio异步编程
- Google Earth engine (GEE) - gpwv411: data set of average administrative unit area
- 8、 Chain mode
- Uncaught TypeError: Cannot read properties of undefined (reading ‘colspan‘)
- axure弹框设置
- June training (day 10) - bit operation
- 5G 聯通網管設計思路
- 【图像去噪】基于matlab BdCNN图像去噪【含Matlab源码 1866期】
- Example 3 of lambda expression
- Composite mode example
猜你喜欢

【730. 统计不同回文子序列】

一个独特的简历生成器,开源了!

Uncaught TypeError: Cannot read properties of undefined (reading ‘colspan‘)

Do you know all the wonderful functions of the vlookup function?

2021 ciscn-pwn 初赛

selenium分布式测试

Some problems in using message queue service in thinkphp6

What are the tools and software needed for SCM development

Browser cache forbidden explanation

MongoDB 发布“可查询加密”系统 Queryable Encryption
随机推荐
How long has elapsed to show the time
R language uses lmperm package to apply to the replacement method (replacement test and permutation tests) of linear model, uses LM model to build polynomial regression model, and uses LMP function to
FinalShell的下载和使用
Notes to docker advanced (6) master-slave replication of MySQL in docker
[golang] input and condition control through BMI index learning console
张小白教你使用OGG实现Oracle 19C到MySQL 5.7的数据同步(3)
[Blue Bridge Cup training 100 questions] scratch apple is ripe blue bridge cup scratch competition special prediction programming question intensive training simulation exercise question 13
隐私计算重要技术突破!亿级数据密态分析可在10分钟内完成
6、 Observer mode
Example 4 of lambda expression
Flutter:自定义单选按钮
Uncaught TypeError: Cannot read properties of undefined (reading ‘colspan‘)
2022年金属非金属矿山提升机操作考试题库及答案
微软再曝“丑闻”:在办公室看 VR 黄片,“HoloLens 之父”即将离职!
九、委托模式
有人用这份抖音电商营销玩法拿下offer 月薪2W
MONGOREPLAY 的“坑”
单片机开发需要的工具以及软件有哪些
[fishing artifact] UI library second to second lowcode tool - list part (II) small tool for maintaining JSON
R language uses coin package to apply permutation tests to continuous variable independence problems, Wilcoxon rank sum test and Wilcox in permutation test on the same data set_ Test exact test