配置過程
- 首先註冊完成極光用戶,登入官網進行創建應用。創建完成點擊右邊應用設置(如下圖)
開發過程
- 利用composer下載極光推送php-sdk。打開cmd訪問到項目根目錄輸入composer require jpush/jpush進行安裝即可。
- 創建一個測試控制器類進行測試
<?php
namespace app\api\controller;
use JPush\Client as JPush;
use JPush\Exceptions\APIConnectionException;
use JPush\Exceptions\APIRequestException;
require_once './vendor/jpush/jpush/autoload.php';
class JPushTest extends Controller
{
public function test()
{
$app_key = "xxx";
$master_secret = "xxx";
//進行極光推送
$client = new JPush($app_key, $master_secret);
try {
$response = $client->push()
->setPlatform(array('ios', 'android'))
// 一般情況下,關於 audience 的設置只需要調用 addAlias、addTag、addTagAnd 或 addRegistrationId
// 這四個方法中的某一個即可,這裏僅作爲示例,當然全部調用也可以,多項 audience 調用表示其結果的交集
// 即是說一般情況下,下面三個方法和沒有列出的 addTagAnd 一共四個,只適用一個便可滿足大多數的場景需求
->addAlias('xxxx')
->addTag(array('xxx'))
//->addRegistrationId($jpush_key)//$jpush_key此處jpush_key是手機端的
//->setNotificationAlert('Hi, JPush')
->iosNotification('測試', array(
'sound' => 'sound.caf',
'badge' => '+1',
'content-available' => true,
'mutable-content' => true,
'category' => 'jiguang',
'extras' => array(
'key' => 'value'
),
))
->message('測試', array(
'title' => '測試',
'content_type' => 'text',
'extras' => array(
'key' => 'value'
),
))
->options(array(
// sendno: 表示推送序號,純粹用來作爲 API 調用標識,
// API 返回時被原樣返回,以方便 API 調用方匹配請求與返回
// 這裏設置爲 100 僅作爲示例
// 'sendno' => 100,
// time_to_live: 表示離線消息保留時長(秒),
// 推送當前用戶不在線時,爲該用戶保留多長時間的離線消息,以便其上線時再次推送。
// 默認 86400 (1 天),最長 10 天。設置爲 0 表示不保留離線消息,只有推送當前在線的用戶可以收到
// 這裏設置爲 1 僅作爲示例
// 'time_to_live' => 1,
// apns_production: 表示APNs是否生產環境,
// True 表示推送生產環境,False 表示要推送開發環境;如果不指定則默認爲推送生產環境
'apns_production' => true,
// big_push_duration: 表示定速推送時長(分鐘),又名緩慢推送,把原本儘可能快的推送速度,降低下來,
// 給定的 n 分鐘內,均勻地向這次推送的目標用戶推送。最大值爲1400.未設置則不是定速推送
// 這裏設置爲 1 僅作爲示例
// 'big_push_duration' => 1
))
->send();
dump($response);
} catch (APIConnectionException $e) {
dump($e->getMessage());
} catch (APIRequestException $e) {
dump($e->getMessage());
}
}
}
客戶端由前端配置無誤之後。訪問鏈接即可,成功之後會返回
array(3) {
["body"] => array(2) {
["sendno"] => string(10) "1609075934"
["msg_id"] => string(16) "9007232746737994"
}
["http_code"] => int(200)
["headers"] => array(10) {
[0] => string(15) "HTTP/1.1 200 OK"
["Server"] => string(5) "nginx"
["Date"] => string(29) "Thu, 05 Dec 2019 09:09:46 GMT"
["Content-Type"] => string(16) "application/json"
["Content-Length"] => string(2) "51"
["Connection"] => string(10) "keep-alive"
["X-Rate-Limit-Limit"] => string(3) "600"
["X-Rate-Limit-Remaining"] => string(3) "599"
["X-Rate-Limit-Reset"] => string(2) "60"
["X-Jpush-Timestamp"] => string(13) "1575536986356"
}
}
注意事項
在開發過程我需要最多的話是報JPush\Exceptions\APIRequestException – [1004]: app_key does not exist這個錯誤,原因的話是選錯了Key跟Secret(我是從賬戶信息進去看到key跟Secret的)。