看了下騰訊雲推送的文件,沒有php的sdk,只好自己寫了
- 封裝類
<?php
/**
* Created by PhpStorm.
* User: wqg
* Date: 2019-03-04
* Time: 12:45
*/
namespace App\Utility;
use App\Models\User;
class Push
{
//騰訊的推送服務,安卓和ios兩個端對應是兩個應用,當後端推送時,無法知道使用者是ios裝置還是安卓裝置,只能兩端都傳送一下
private $android_access_id = '';
private $android_secret_key = '';
private $ios_access_id = '';
private $ios_secret_key = '';
private $url = 'https://api.tpns.tencent.com/v3/push/app';
//簽名
public function sign($body,$time, $type = 'android')
{
if ($type == 'android') {
$str = $time . $this->android_access_id . $body;
var_dump($str);
return base64_encode(hash_hmac('sha256', $str, $this->android_secret_key));
} else {
$str = $time . $this->ios_access_id . $body;
var_dump($str);
return base64_encode(hash_hmac('sha256', $str, $this->ios_secret_key));
}
}
/**
* @param $user_id
* @param $title
* @param $content
* @param array $params
* @return bool|mixed
* 傳送訊息至安卓裝置
*/
public function sendToAndroid($user_id, $title, $content, $params = [])
{
$user = User::find($user_id);
if (!$user || !$user->tpns_token) {
//獲取使用者推送的唯一標示
return false;
}
$message = [
'title' => $title,
'content' => $content,
];
if (count($params)) {
$message['android']['custom_content'] = json_encode($params);
}
$data = [
'audience_type' => 'token',
'token_list' => [$user->tpns_token],
'message_type' => 'notify',
'message' => $message,
];
$time = time();
$data = json_encode($data, JSON_UNESCAPED_UNICODE);
$sign = $this->sign($data, $time, 'android');
$header = [
'AccessId:'.$this->android_access_id,
'TimeStamp:'.$time,
'Sign:'.$sign
];
return httpRequest($this->url,$data,false,$header );
}
/**
* @param $user_id
* @param $title
* @param $content
* @param array $params
* @return bool|mixed
* 傳送推送至ios裝置
*/
public function sendToIos($user_id, $title, $content, $params = [])
{
$user = User::find($user_id);
if (!$user || !$user->tpns_token) {
return false;
}
$message = [
'title' => $title,
'content' => $content,
'ios' => [
'aps' => [
'badge_type' => 1,
]
]
];
if (count($params)) {
$message['ios']['custom_content'] = json_encode($params);
}
$data = [
'audience_type' => 'token',
'token_list' => [$user->tpns_token],
'message_type' => 'notify',
'message' => $message,
'environment' => 'dev'//product
];
$time = time();
$data = json_encode($data, JSON_UNESCAPED_UNICODE);
$sign = $this->sign($data, $time, 'ios');
$header = [
'AccessId:'.$this->ios_access_id,
'TimeStamp:'.$time,
'Sign:'.$sign
];
return httpRequest($this->url,$data,false,$header );
}
}
- 呼叫
$push = new \App\Utility\Push(); $push->sendToIos($this->user_id,$this->title,$this->content,$this->params); $push->sendToAndroid($this->user_id,$this->title,$this->content,$this->params);
本作品採用《CC 協議》,轉載必須註明作者和本文連結