### Signature Base String Example
Source: https://push.baidu.com/doc/restapi/sdk_developer
Example of the concatenated string used before MD5 hashing for signature generation.
```text
POSThttp://api.tuisong.baidu.com/rest/3.0/test/echoapikey=Ljc710pzAa99GULCo8y48NvBexpires=1313293565timestamp=142718090587772555E1C16715EBA5C85341684C58
```
--------------------------------
### Start Push Service
Source: https://push.baidu.com/doc/android/api
Initializes the Push service and performs binding. Do not call this method within Application.onCreate().
```java
public static void startWork(Context context, int loginType, String loginValue);
```
--------------------------------
### Add Devices to Tag Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response for the add_devices endpoint.
```json
{
"request_id":123456789,
"response_params":{
"devices":[
{
"channel_id":"43848320940932",
"result":0
},
{
"channel_id":"48302948302432043",
"result":1
},
...
]
}
}
```
--------------------------------
### Create Tag Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response for the create_tag endpoint.
```json
{
"request_id":123456789,
"response_params":{
"tag":"tag_name",
"result":0
}
}
```
--------------------------------
### Query Tag Device Count Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response for the device_num endpoint.
```json
{
"request_id":123456789,
"response_params":{
"device_num":1000
}
}
```
--------------------------------
### Query Topic List Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response for the /rest/3.0/topic/query_list endpoint.
```json
{
"request_id":123456789,
"response_params":{
"total_num":10,
"topics":[
{
"topic_id":"1000",
"ctime":1421247101,
"mtime":1421247101,
"push_cnt":2000,
"ack_cnt":1000,
},
...
]
}
}
}
```
--------------------------------
### Query Scheduled Task List Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response for the query_list timer endpoint.
```json
{
"request_id":123456789,
"response_params":{
"total_num":10,
"result":[
{
"timer_id":1000,
"msg":"message body",
"msg_type":0,
"range_type":2,
"send_time":147456789
},
...
]
}
}
```
--------------------------------
### Batch Device Push Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response structure for the batch device push endpoint.
```json
{
"request_id":123456789,
"response_params":
{
"msg_id":"24234532453245",
"send_time":12345678
}
}
```
--------------------------------
### Device Statistics Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response for the /rest/3.0/report/statistic_device endpoint.
```json
{
"request_id" : 500348335,
"response_params" : {
"total_num" : 180,
"result" : {
"1429977600" : {
"new_term" : 2,
"del_term" : 115,
"online_term" : 178,
"addup_term" : 103,
"total_term" : 193
},
...
}
}
};
```
--------------------------------
### Query Tag List Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response for the query_tags endpoint.
```json
{
"request_id":123456789,
"response_params":{
"total_num":100,
"tags":[
{
"tid":1000,
"tag":"tag1",
"info":"tag1",
"type":0,
"createtime":140233424
},
...
]
}
}
```
--------------------------------
### Topic Statistics Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response for the /rest/3.0/report/statistic_topic endpoint.
```json
{
"request_id" : 500335275,
"response_params" : {
"total_num" : 120,
"result" : {
"1429977600" : {
"ack" : 111
},
...
}
}
}
```
--------------------------------
### Push Message to Single Device Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response structure for the single device push API.
```json
{
"request_id":123456789,
"response_params":
{
"msg_id":24234532453245,
"send_time":1427174155
}
}
```
--------------------------------
### Huawei Push Service JWT Token Configuration
Source: https://push.baidu.com/doc/guide/manufacturer
Example of the service account key file structure required for authentication with Huawei Push services.
```json
{
"project_id": "*****",
"key_id": "*****",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIJQgIBADANBgkqhkiG9w0BAQEFAASCCSwwggkoAgEAAoICAQCKw6kJKtCh7qmMvp1u1dI27z2TKZrPOzHbQaXO/Eez0AWZ2EN+ouF496R3pfo7fQXC1XOT/YTbVC4DNZwWSMA54fu3/AOCY9Zzyi46OK*****==\n-----END PRIVATE KEY-----\n",
"sub_account": "*****",
"auth_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/authorize",
"token_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/token",
"auth_provider_cert_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/certs",
"client_cert_uri": "https://oauth-login.cloud.huawei.com/oauth2/v3/x509?client_id=*****"
}
```
--------------------------------
### Get Binding Information
Source: https://push.baidu.com/doc/ios/api
Retrieves the appId, channelId, and userId after a successful binding. Returns empty strings if not bound.
```objective-c
+ (NSString *) getChannelId;
+ (NSString *) getUserId;
+ (NSString *) getAppId;
```
--------------------------------
### startWork
Source: https://push.baidu.com/doc/android/api
Initializes the Push service and performs the bind operation.
```APIDOC
## public static void startWork(Context context, int loginType, String loginValue)
### Description
Initializes the Push service and automatically performs the bind operation. Do not call this in Application.onCreate().
### Parameters
- **context** (Context) - Required - The current execution context.
- **loginType** (int) - Required - The binding authentication method (e.g., PushConstants.LOGIN_TYPE_API_KEY).
- **loginValue** (String) - Required - The application's API Key.
```
--------------------------------
### Initialize PushSDK
Source: https://push.baidu.com/doc/php/api
Create a new instance of the PushSDK using your application's API key and secret key.
```php
$ak = 'ak of your app';
$sk = 'sk of your app';
$sdk = new PushSdk($ak,$sk);
// to do something...
```
--------------------------------
### PushSDK::__Constructor
Source: https://push.baidu.com/doc/php/api
Creates a new instance of the PushSDK.
```APIDOC
## PushSDK::__Constructor
### Description
Creates a new PushSDK instance to interact with the push service.
### Parameters
- **apiKey** (string) - Optional - Developer API key.
- **secretKey** (string) - Optional - Developer secret key.
- **curlopts** (array) - Optional - Configuration options for cUrl.
```
--------------------------------
### PushManager.startWork
Source: https://push.baidu.com/doc/android/api
Initializes the Baidu Push service within the application.
```APIDOC
### PushManager.startWork
### Description
Initializes the Baidu Push service. This should be called in the onCreate method of the main Activity.
### Parameters
- **context** (Context) - Required - The application context.
- **loginType** (int) - Required - The login type, typically PushConstants.LOGIN_TYPE_API_KEY.
- **apiKey** (String) - Required - The API Key for the application.
```
--------------------------------
### Cancel Scheduled Task Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response for the /rest/3.0/timer/cancel endpoint.
```json
{
"request_id":12394838223,
}
```
--------------------------------
### 配置 SDK 凭证
Source: https://push.baidu.com/doc/php/quick_start
在configure.php中设置API Key和Secret Key,用于身份验证。
```php
/**
* 开发者apikey, 由开发者中心(http://developer.baidu.com)获取,
* 当代码中未设置apikey时,使用此apikey
* @var string
*/
const default_apiKey = 'Vek7uG4nhplvh3cpg2H5Ut50';
/**
* 开发者当前secretKey, 在应用重新生成secret key后, 旧的secret key将失效, 由开发者中心(http://developer.baidu.com)获取.
* 当代码中未设置apikey时,使用此secretkey
* @var string
*/
const default_secretkey = 'NdxoxNykVrH6qA3CV33kzK7lsSTTvZA9';
```
--------------------------------
### 运行 SDK 环境测试
Source: https://push.baidu.com/doc/php/quick_start
使用phpunit执行环境检查脚本,确认SDK配置及运行环境正常。
```bash
> cd test
> phpunit check_sdk_test.php
PHPUnit 4.4.1 by Sebastian Bergmann.
.
SDK_HOME:/home/rd/phpsdk/
CONFIG_FILE:/home/rd/phpsdk/configure.php
[INFO][1425960087][PUSH_SDK] PushSimpleLog: ready to work!;
[INFO][1425960087][PUSH_SDK] HttpRequest: ready to work...;
[INFO][1425960087][PUSH_SDK] SDK: initializing...;
[INFO][1425960087][PUSH_SDK] SDK ready to work !!;
[INFO][1425960088][PUSH_SDK] HttpRequest: 200 POST http://api.tuisong.baidu.com/rest/3.0/push/single_device;
[INFO][1425960088][PUSH_SDK] Parse Response: 200, OK, {"request_id":804656752,"response_params":{"msg_id":"3570960677660087563","send_time":1425960086}};
.finish the test and every thing is good!
```
```text
Time: 996 ms, Memory: 4.00Mb
OK (2 tests, 6 assertions)
```
--------------------------------
### Initialize Push SDK in Activity
Source: https://push.baidu.com/doc/android/api
Enable vendor proxies and initialize the push service within the onCreate method of your main Activity.
```java
// 开启华为代理,如需开启,请参考华为厂商接入文档
PushManager.enableHuaweiProxy(this, true);
// 开启魅族代理,如需开启,请参考魅族厂商接入文档
PushManager.enableMeizuProxy(this, true, "mzAppid", "mzAppKey");
// 开启OPPO代理,如需开启,请参考OPPO厂商接入文档
PushManager.enableOppoProxy(this, true, "oppoAppKey", "oppoAppSecret");
// 开启小米代理,如需开启,请参考小米厂商接入文档
PushManager.enableXiaomiProxy(this, true, "xmAppId", "xmAppKey");
// 开启VIVO代理,如需开启,请参考VIVO厂商接入文档
PushManager.enableVivoProxy(this, true);
// 开启荣耀代理,参考荣耀厂商文档
PushManager.enableHonorProxy(this, true);
// 初始化PUSH
PushManager.startWork(getApplicationContext(),PushConstants.LOGIN_TYPE_API_KEY,"api_key");
```
--------------------------------
### Create Tag and Add Devices
Source: https://push.baidu.com/doc/php/api
Demonstrates creating a new tag, adding multiple devices to it, and sending a message to the tag group.
```php
/创建一个有五个设备的组,并向该组发送一条消息。
// 创建消息内容
$msg = array(
'description' => 'notice msg',
);
// 消息控制选项。
$opts = array(
'msg_type' => 1
);
// 发送给以下五个设备,每个设备ID应与终端设备上产生的 channel_id 一一对应。
$idArr = array(
'000000000000001',
'000000000000002',
'000000000000003',
'000000000000004',
'000000000000005',
);
$rs = $sdk->createTag('tag_new');
if($rs !== false){
if($sdk -> addDevicesToTag('tag_new',$idArr) !== false){
// 发送
$rs = $sdk -> pushMsgToTag('tag_new',$msg,$opts);
// check result and other something。
// ....
}
}
```
--------------------------------
### Query Device Count in Tag
Source: https://push.baidu.com/doc/python/api
Demonstrates creating a tag, adding devices to it, and querying the device count within that tag.
```python
# 要向tag中添加的两个设备
channel_ids = ["0000000000000000001", "0000000000000000002"]
c = Channel()
try:
ret = c.createTag('tag_new')
ret_2 = c.addDevicesToTag('tag_new', channel_ids)
ret_3 = c.queryDeviceNumInTag('tag_new')
print ret_3 # 将打印出相关信息
except ChannelException as e:
print e.getLastErrorMsg()
```
--------------------------------
### Initialize BaiduPushClient
Source: https://push.baidu.com/doc/java/quick_start
Instantiate the BaiduPushClient to interact with the SDK interfaces.
```java
BaiduPushClient pushClient = new BaiduPushClient(pair,
BaiduPushConstants.CHANNEL_REST_URL);
```
--------------------------------
### Push Multicast Message Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response structure for the multicast message push API.
```json
{
"request_id":123456789,
"response_params":
{
"msg_id":"24234532453245",
"send_time": 1428156644
}
}
```
--------------------------------
### Initialize PushKeyPair
Source: https://push.baidu.com/doc/java/quick_start
Create a PushKeyPair using your application's API key and Secret key.
```java
String apiKey = “xxxxxxxxxxxxxxxxxxxxxx”;
String secretKey = “xxxxxxxxxxxxxxxxxxxxxx”;
PushKeyPair pair = new PushKeyPair(apiKey,secretKey);
```
--------------------------------
### Push Broadcast Message Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response structure for the broadcast message push API.
```json
{
"request_id":123456789,
"response_params":
{
"msg_id":"24234532453245",
"send_time":1428156644
}
}
```
--------------------------------
### Message Status Query Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response structure for querying the status of a specific message ID.
```json
{
"request_id":123456789,
"response_params":{
total_num:10,
result:[{
"msg_id":"24234532453245",
"status":0,
"success":10000,
"send_time":1472354868
}]
}
}
```
--------------------------------
### 将 p12 证书转换为 pem 格式
Source: https://push.baidu.com/doc/ios/api
使用 OpenSSL 将导出的 .p12 证书文件转换为 .pem 格式,以便在服务器端使用。执行时需输入导出 p12 文件时设置的密码。
```bash
openssl pkcs12 -in MyApnsCert.p12 -out MyApnsCert.pem -nodes
```
--------------------------------
### 下载与解压 PHP SDK
Source: https://push.baidu.com/doc/php/quick_start
使用wget下载SDK压缩包并使用tar命令进行解压。
```bash
> wget http://push.baidu.com/project/download/push_server_sdk_for_php?redirect=yes
```
```bash
> tar zxvf php-sdk.tar.gz
```
--------------------------------
### 发送第一条推送消息
Source: https://push.baidu.com/doc/php/quick_start
实例化PushSDK并调用pushMsgToSingleDevice方法向指定设备发送通知。
```php
require_once './phpsdk/sdk.php';
// 创建SDK对象.
$sdk = new PushSDK();
$channelId = '3785562685113372034';
// 消息内容.
$message = array (
// 消息的标题.
'title' => 'Hi!.',
// 消息内容
'description' => "hello!, this message from baidu push service."
);
// 设置消息类型为 通知类型.
$opts = array (
'msg_type' => 1
);
// 向目标设备发送一条消息
$rs = $sdk -> pushMsgToSingleDevice($channelId, $message, $opts);
// 判断返回值,当发送失败时, $rs的结果为false, 可以通过getError来获得错误信息.
if($rs === false){
print_r($sdk->getLastErrorCode());
print_r($sdk->getLastErrorMsg());
}else{
// 将打印出消息的id,发送时间等相关信息.
print_r($rs);
}
echo "done!";
```
--------------------------------
### Execute Push Request
Source: https://push.baidu.com/doc/java/quick_start
Send the configured request using the BaiduPushClient.
```java
PushMsgToSingleDeviceResponse response = pushClient.
pushMsgToSingleDevice(request);
```
--------------------------------
### Scheduled Message Record Query Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response structure for retrieving records of scheduled messages by timer ID.
```json
{
"request_id":123456789,
"response_params":
{
"timer_id":1011,
"result":[
{
"msg_id":"24234532453245",
"status":0,
"send_time":147456789
},
......
]
}
}
```
--------------------------------
### Configure Android SDK Dependencies
Source: https://push.baidu.com/doc/android/api
Add the Baidu Push SDK and various manufacturer push SDKs to your project's build configuration.
```gradle
// 本地依赖百度Push SDK
implementation(name:'baidu-push-sdk-8.3.68.0-ext', ext:'aar')
// VIVO、OPPO、小米、魅族厂商 push sdk 本地依赖
implementation(name:'vivo_pushSDK_v3.0.0.6_486', ext:'aar')
implementation(name:'MiPush_SDK_Client_6_0_2-C_3rd', ext:'aar')
implementation(name:'MzPushSDK-4.2.7', ext:'aar')
implementation(name:'OPPOPushSDK-3.1.0', ext:'aar')
implementation(name:'HiPushSdk-7.0.61.303',ext:'aar')
// 华为,需要依赖华为maven仓库,
implementation 'com.huawei.hms:push:6.5.0.300'
// oppo push sdk依赖第三方lib
implementation 'com.google.code.gson:gson:2.6.2'
implementation 'commons-codec:commons-codec:1.6'
implementation 'androidx.annotation:annotation:1.1.0'
```
--------------------------------
### Topic-based Message Record Query Response
Source: https://push.baidu.com/doc/restapi/restapi
Example response structure for retrieving message records associated with a specific topic ID.
```json
{
"request_id":123456789,
"response_params":
{
"topic_id":"1011",
"result":[
{
"msg_id":"24234532453245",
"status":0,
"send_time":147456789
},
…
]
}
}
```
--------------------------------
### Configure Push Request Parameters
Source: https://push.baidu.com/doc/java/quick_start
Create and configure a PushMsgToSingleDeviceRequest instance with message details and device settings.
```java
PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest().
addChannelId("xxxxxxxxxxxxxxxxxx").
addMsgExpires(new Integer(3600)). //设置消息的有效时间,单位秒,默认3600 x 5.
addMessageType(1). //设置消息类型,0表示消息,1表示通知,默认为0.
addMessage("{\"title\":\"TEST\",\"description\":\"Hello Baidu push!\"}").
addDeviceType(3); //设置设备类型,3 for android, 4 for ios.
```
--------------------------------
### Bind and Unbind Channel
Source: https://push.baidu.com/doc/ios/api
Methods to bind or unbind the push service channel. Binding requires prior setup of credentials and device tokens.
```objective-c
+ (void)bindChannelWithCompleteHandler:(BPushCallBack)handler;
+ (void)unbindChannelWithCompleteHandler:(BPushCallBack)handler;
```
--------------------------------
### 注册推送服务接口
Source: https://push.baidu.com/doc/guide/faq_ios
在注册推送服务时,需根据开发或生产环境正确设置BPushMode参数。
```objective-c
+(void)registerChannel:(NSDictionary)launchOptions apiKey:(NSString )apikey pushMode:(BPushMode)mode withFirstAction:(NSString )leftAction withSecondAction:(NSString )rightAction withCategory:(NSString *)category isDebug:(BOOL)isdebug
```
--------------------------------
### POST /rest/3.0/push/all
Source: https://push.baidu.com/doc/restapi/restapi
向当前 app 下所有设备推送一条消息。
```APIDOC
## [POST] /rest/3.0/push/all
### Description
向当前 app 下所有设备推送一条消息。
### Method
POST
### Endpoint
/rest/3.0/push/all
### Parameters
#### Request Body
- **msg_type** (number) - Optional - 消息类型(0:消息, 1:通知)
- **msg** (string) - Required - 消息内容,json格式
- **extra_msg_type** (number) - Optional - 消息类型(0:消息, 1:通知)
- **extra_msg** (string) - Optional - 消息内容,json格式
- **msg_expires** (number) - Optional - 消息过期时间(秒)
- **deploy_status** (number) - Optional - iOS部署状态(1:开发, 2:生产)
- **send_time** (number) - Optional - 定时推送时间
### Response
#### Success Response (200)
- **msg_id** (string) - 该条消息ID
- **timer_id** (string) - 定时任务ID
- **send_time** (number) - 消息的实际推送时间
### Response Example
{
"request_id": 123456789,
"response_params": {
"msg_id": "24234532453245",
"send_time": 1428156644
}
}
```
--------------------------------
### Set No-Disturb Mode
Source: https://push.baidu.com/doc/android/api
Defines a time window for no-disturb mode where notifications will not trigger sound, vibration, or lights. If start time equals end time (00:00), the feature is disabled.
```java
PushManager.setNoDisturbMode(Context context, int startHour, int startMinute, int endHour, int endMinute);
```
--------------------------------
### Initialize Notification Builders
Source: https://push.baidu.com/doc/android/api
Constructors for basic and custom notification builders.
```java
BasicPushNotificationBuilder();
```
```java
CustomPushNotificationBuilder(layoutId, layoutIconId, layoutTitleId, layoutTextId);
```
--------------------------------
### Query Scheduled Push Tasks
Source: https://push.baidu.com/doc/php/api
Demonstrates creating a scheduled broadcast message and querying the timer list to verify the task status.
```php
// 发送一条5分钟后的定时广播消息. 并即时查看任务状态。
// 创建消息内容
$msg = array(
'description' => 'notice msg',
);
// 消息控制选项。
$opts = array(
'msg_type' => 1,
'send_time' => time() + 5 * 60
);
// 发送
$rs = $sdk -> pushMsgToAll($msg,$opts);
if($rs !== false){
print_r($rs); // 将打印出 msg_id,timer_id 及 timestamp
$timer_id = $rs['timer_id'];
$list = $sdk -> queryTimerList();
if($list !== false && $list -> total_num > 0){
foreach($list as $item){
if($item['timer_id'] === $timer_id)){
print_r($item); //将打印相关信息。
}
}
}
}
```
--------------------------------
### Create and Delete Tag
Source: https://push.baidu.com/doc/python/api
Demonstrates the lifecycle of creating and subsequently deleting a tag group.
```python
# 创建一个组,随后删除。
c = Channel()
try:
ret = c.createTag('test_tag')
print ret
ret = c.deleteTag('test_tag')
print ret
except ChannelException as e:
print e.getLastErrorMsg()
```
--------------------------------
### enableXiaomiProxy
Source: https://push.baidu.com/doc/android/api
Configures whether to enable the Xiaomi proxy mode for push services.
```APIDOC
## public static void enableXiaomiProxy(Context context, boolean proxyEnable, String appId, String appKey)
### Description
Enables or disables the Xiaomi proxy mode for the push service.
### Parameters
- **context** (Context) - Required - The current execution context.
- **proxyEnable** (boolean) - Required - Whether to enable Xiaomi proxy mode.
- **appId** (String) - Required - The app ID from the Xiaomi push platform.
- **appKey** (String) - Required - The app key from the Xiaomi push platform.
```
--------------------------------
### Create and Delete Tag Groups
Source: https://push.baidu.com/doc/php/api
Demonstrates the lifecycle of a tag group by creating it and subsequently deleting it.
```php
// 创建一个组,随后删除。
$rs = $sdk -> createTag('tmpTag');
if($rs !== false && $rs['result'] === 0){ //判断是否创建成功
echo "create tag ok! \n";
$delRs = $sdk->deleteTag('tmpTag');
if($rs !== false && $rs['result'] === 0){ //判断是否删除成功
echo "delete tag ok! \n";
}
}
```
--------------------------------
### Query Timer List
Source: https://push.baidu.com/doc/python/api
Lists information for pending scheduled push tasks.
```python
# 发送一条5分钟后的定时广播消息. 并即时查看任务状态。
# 创建消息内容
msg = 'msg to all'
# 消息控制选项,5min后发送
opts = {'msg_type':0, 'expires':300, 'send_time':int(time.time()) + 300}
c = Channel()
# 发送
try:
ret = c.pushMsgToAll(msg, opts)
timer_id = ret['timer_id']
ret_2 = c.queryTimerList()
print ret_2 # 将打印出默认筛选条件下的定时信息状态
except ChannelException as e:
print e.getLastErrorMsg()
```
--------------------------------
### Enable HONOR Proxy
Source: https://push.baidu.com/doc/android/api
Configures the HONOR proxy mode.
```java
public static void enableHonorProxy(Context context, boolean proxyEnable);
```
--------------------------------
### registerChannel:apiKey:pushMode:withFirstAction:withSecondAction:withCategory:useBehaviorTextInput:isDebug:
Source: https://push.baidu.com/doc/ios/api
Registers the Baidu Push service for the application.
```APIDOC
## registerChannel
### Description
Registers the Baidu Push service with the provided configuration.
### Signature
`+ (void)registerChannel:(NSDictionary *)launchOptions apiKey:(NSString *)apikey pushMode:(BPushMode)mode withFirstAction:(NSString *)rightAction withSecondAction:(NSString *)leftAction withCategory:(NSString *)category useBehaviorTextInput:(BOOL)behaviorTextInput isDebug:(BOOL)isdebug;`
```
--------------------------------
### Enable VIVO Proxy
Source: https://push.baidu.com/doc/android/api
Configures the VIVO proxy mode.
```java
public static void enableVivoProxy(Context context, boolean proxyEnable);
```
--------------------------------
### User-Agent Header Format
Source: https://push.baidu.com/doc/restapi/sdk_developer
Required format for the User-Agent header to identify the SDK environment.
```text
BCCS_SDK/3.0 (操作系统版本信息) 开发语言/开发语言版本 (SDK名称及版本信息) 其它扩展模块/版本(附加信息)
```
```text
User-Agent: BCCS_SDK/3.0 (Darwin; Darwin Kernel Version 14.0.0: Fri Sep 19 00:26:44 PDT 2014; root:xnu-2782.1.97~2/RELEASE_X86_64; x86_64) PHP/5.6.3 (Baidu Push Server SDK V3.0.0 and so on..) cli/Unknown ZEND/2.6.0
```
--------------------------------
### Register BPush Service
Source: https://push.baidu.com/doc/ios/api
Registers the application with the Baidu Push service using launch options and API credentials.
```objective-c
+ (void)registerChannel:(NSDictionary *)launchOptions apiKey:(NSString *)apikey pushMode:(BPushMode)mode withFirstAction:(NSString *)rightAction withSecondAction:(NSString *)leftAction withCategory:(NSString *)category useBehaviorTextInput:(BOOL)behaviorTextInput isDebug:(BOOL)isdebug;
```
--------------------------------
### 测试 APNs 证书连接
Source: https://push.baidu.com/doc/ios/api
使用 OpenSSL 测试开发或生产环境的推送证书是否有效。
```bash
openssl s_client -connect api.sandbox.push.apple.com:443 -cert MyApnsDev.pem
```
```bash
openssl s_client -connect api.push.apple.com:443 -cert MyApnsPro.pem
```
--------------------------------
### Enable OPPO Proxy
Source: https://push.baidu.com/doc/android/api
Configures the OPPO proxy mode using the provided app credentials.
```java
public static void enableOppoProxy(Context context, boolean proxyEnable, String appKey, String appSecret);
```
--------------------------------
### bindChannelWithCompleteHandler
Source: https://push.baidu.com/doc/ios/api
Binds the current device to the push service.
```APIDOC
## + (void)bindChannelWithCompleteHandler:(BPushCallBack)handler
```
--------------------------------
### Enable Huawei Proxy
Source: https://push.baidu.com/doc/android/api
Configures the Huawei proxy mode for the Push service.
```java
public static void enableHuaweiProxy(Context context, boolean proxyEnable);
```
--------------------------------
### Enable Xiaomi Proxy
Source: https://push.baidu.com/doc/android/api
Configures the Xiaomi proxy mode using the provided app credentials.
```java
public static void enableXiaomiProxy(Context context,boolean proxyEnable, String appId, String appKey);
```
--------------------------------
### 配置测试 Channel ID
Source: https://push.baidu.com/doc/php/quick_start
在configure.php中指定用于接收测试消息的设备Channel ID。
```php
/**
* 用于接收测试消息的channel_id.
* @var string
*/
const test_channel_id = '3785562685113372034';
```
--------------------------------
### 服务端错误码列表
Source: https://push.baidu.com/doc/restapi/error_code
百度云推送服务端API错误码对照表,包含错误代码、错误信息、描述及HTTP状态码。
```APIDOC
## 服务端错误码
| Error_Code | Error_Message | Description | Http_Status |
|---|---|---|---|
| 无 | 无 | 成功 | 200 |
| 30600 | Internal Server Error | 服务内部错误 | 500 |
| 30601 | Method Not Allowed | 请求方法不允许 | 405 |
| 30602 | Request Params Not Valid | 请求参数错误 | 400 |
| 30603 | Authentication Failed | 权限验证失败 | 403 |
| 30604 | Quota Use Up Payment Required | 配额用尽需要续费 | 402 |
| 30605 | Data Required Not Found | 请求数据不存在 | 404 |
| 30606 | Request Time Expires Timeout | 请求时间戳验证超时 | 408 |
| 30607 | Channel Token Timeout | 服务令牌有效期超时 | 408 |
| 30608 | Bind Relation Not Found | 绑定关系未找到或不存在 | 404 |
| 30609 | Bind Number Too Many | 绑定关系太多 | 404 |
| 30610 | Duplicate Operation | 重复操作 | 409 |
| 30611 | Tag not Found | Tag未找到或不存在 | 404 |
| 30612 | Application Forbidden, Need Whitelist Authorization | 应用被禁止,需要白名单授权 | 401 |
| 30613 | App Need Inited First In Push Console | 需要先在Push-Console开通推送功能 | 402 |
| 30616 | Application Is Not approved, Can Not Use The Push Service | 未审核通过,应用无法使用推送服务 | 401 |
| 30617 | Application Do Not Have Broadcast Push Capability | 应用没有广播推送能力 | 401 |
| 30618 | Application Do Not Have Unicast Or Grpcast Push Capability | 应用没有单播或组播推送能力 | 401 |
| 30619 | Default Tag Is Reserved | 不允许操作default tag | 403 |
| 30620 | One App Could Only Have One Kind Of Device Platform | 一个应用只支持一个设备平台 | 403 |
| 30621 | Package Name Invalid | android包名非法 | 400 |
| 30699 | Requests Are Too Frequent To Be Temporarily Rejected Or Need Whitelist Authorization | 请求太频繁而被临时拒绝或者需要白名单授权 | 402 |
| 40001 | Invalid iOS Device Token | Device Token格式不合法 | 400 |
| 40002 | Invalid iOS Message | 无效的消息格式 | 400 |
| 40003 | iOS Bad Device Token | APNS认为Device Token已经失效 | 400 |
| 40004 | iOS Certification Error | 证书错误,连接被APNs拒绝 | 400 |
| 40005 | iOS Duplicate Message | 重复消息 | 400 |
| 40006 | iOS Production Cert Invalid | 生产版证书无效 | 400 |
| 40007 | iOS Development Cert Invalid | 开发版证书无效 | 400 |
| 40008 | iOS Production Cert Expire | 生产版证书过期 | 400 |
| 40009 | iOS Development Cert Expire | 开发版证书过期 | 400 |
| 40010 | Cert Type Error, Need A Development Cert | 需要开发版证书,错误上传了生产版证书 | 400 |
| 40011 | Cert Type Error, Need A Production Cert | 需要生产版证书,错误上传了生产版证书 | 400 |
| 40012 | iOS Cert File Invalid | iOS证书不合法 | 400 |
| 41001 | Timer Task Not Exist | 定时任务不存在 | 400 |
| 41002 | Timer Task Duplicated | 定时任务重复 | 400 |
| 41003 | Timer Task Num Exceed | 定时任务数超限 | 400 |
| 41004 | Timer Task Will Be Executed, Can Not Be Canceled | 定时任务将要执行,不允许取消 | 400 |
| 41005 | Timer Task Has Been Executed | 定时任务已执行 | 400 |
| 50001 | Generate CSRF Token Failed | 生成CSRF Token失败 | 500 |
| 50002 | Invalid CSRF Token | 无效的CSRF Token | 400 |
| 50003 | CSRF Token Expired | CSRF Token已失效 | 400 |
| 50004 | Passport Not Login | 未登录百度账号passport | 400 |
| 50005 | Invalid BDUSS | 无效的baidu账户Session | 400 |
| 50006 | Required To Register AS A Developer | 不是开发者 | 403 |
| 50007 | Invalid Developer | 开发者无效 | 403 |
| 50008 | Invalid Appname | 应用名非法 | 400 |
```
--------------------------------
### GET/POST /rest/3.0/timer/query_list
Source: https://push.baidu.com/doc/restapi/restapi
Queries the list of scheduled push tasks.
```APIDOC
## [GET | POST] /rest/3.0/timer/query_list
### Description
Queries scheduled push tasks that have not yet been executed.
### Method
GET, POST
### Endpoint
/rest/3.0/timer/query_list
### Parameters
#### Query Parameters
- **timer_id** (string) - Optional - Unique identifier for the task
- **start** (number) - Optional - Starting index
- **limit** (number) - Optional - Number of records to return
### Response
#### Success Response (200)
- **total_num** (number) - Total number of tasks
- **result** (JsonArray) - List of task details
#### Response Example
{
"request_id": 123456789,
"response_params": {
"total_num": 10,
"result": [
{
"timer_id": 1000,
"msg": "message body",
"msg_type": 0,
"range_type": 2,
"send_time": 147456789
}
]
}
}
```
--------------------------------
### registerDeviceToken:
Source: https://push.baidu.com/doc/ios/api
Registers the device token with the Baidu Push service.
```APIDOC
## registerDeviceToken
### Description
Registers the client's device token, which is required for push notifications.
### Signature
`+ (void)registerDeviceToken:(NSData *)deviceToken;`
```
--------------------------------
### Enable Meizu Proxy
Source: https://push.baidu.com/doc/android/api
Configures the Meizu proxy mode using the provided app credentials.
```java
public static void enableMeizuProxy(Context context, boolean proxyEnable, String appId, String appKey);
```
--------------------------------
### PHP Signature Algorithm
Source: https://push.baidu.com/doc/restapi/sdk_developer
Implementation of the signature generation algorithm in PHP.
```php
/**
* $secret_key //应用的secret key
* $method //GET或POST
* $url url
* $arrContent //请求参数(包括GET和POST的所有参数,不含计算的sign)
* return $sign string
**/
function genSign($secret_key, $method, $url, $arrContent) {
$gather = $method.$url;
ksort($arrContent);
foreach($arrContent as $key => $value) {
$gather .= $key.'='.$value;
}
$gather .= $secret_key;
$sign = md5(urlencode($gather));
return $sign;
}
$secret_key = 'xxxxxxxx';//此处替换为应用的secret key
$method = 'POST';
$url = 'http://{domain}/rest/3.0/{class}/{method}';
$arrContent = array(
'apikey'=>'fdafadAfdsafadsDrfeareV',
'timestamp'=>1313293563,
'expires'=>1313293565,
);
$sign = genSign($secret_key, $method, $url, $arrContent);
```
--------------------------------
### Vendor Proxy Configuration
Source: https://push.baidu.com/doc/android/api
Methods to enable third-party vendor push proxies for improved delivery.
```APIDOC
### Vendor Proxy Methods
### Description
Methods to enable specific vendor push proxies. These should be called in the main Activity's onCreate method.
### Methods
- **PushManager.enableHuaweiProxy(Context context, boolean enable)**
- **PushManager.enableMeizuProxy(Context context, boolean enable, String appId, String appKey)**
- **PushManager.enableOppoProxy(Context context, boolean enable, String appKey, String appSecret)**
- **PushManager.enableXiaomiProxy(Context context, boolean enable, String appId, String appKey)**
- **PushManager.enableVivoProxy(Context context, boolean enable)**
- **PushManager.enableHonorProxy(Context context, boolean enable)**
```
--------------------------------
### PushSDK::createTag
Source: https://push.baidu.com/doc/php/api
Creates a new tag group.
```APIDOC
## Method PushSDK::createTag
### Description
Creates a new tag group.
### Parameters
- **tagName** (string) - Required - The name of the tag group, length 1-128 characters.
### Response
- **tagName** (string) - The name of the tag group.
- **result** (int) - 0 for success, 1 for failure.
```
--------------------------------
### Query Tags with PushSDK
Source: https://push.baidu.com/doc/php/api
Retrieves existing tag groups and iterates through the results to display tag information.
```php
$rs = $sdk->queryTags();
if($rs === false){ //确认返回。
//get error。
echo $sdk -> getLastErrorMsg();
echo "/n";
}else if($rs['total_num'] > 0){
foreach($rs['result'] as $item){
extract($item);
echo "tid:$tid; tagname:$tag,createTime:$create_time";
}
}
```
--------------------------------
### bindChannelWithCompleteHandler:
Source: https://push.baidu.com/doc/ios/api
Binds the Push service channel.
```APIDOC
## bindChannelWithCompleteHandler
### Description
Binds the Push service channel. Must be called after setting the Access Token or API Key and registering the device token.
### Signature
`+ (void)bindChannelWithCompleteHandler:(BPushCallBack)handler;`
```
--------------------------------
### Configure Notification Builders
Source: https://push.baidu.com/doc/android/api
Methods for setting custom notification styles and default builders.
```java
public static void setNotificationBuilder(Context context, int id, PushNotificationBuilder notificationBuilder);
```
```java
public static void setDefaultNotificationBuilder(Context context, PushNotificationBuilder notificationBuilder);
```
--------------------------------
### Manage Tags
Source: https://push.baidu.com/doc/ios/api
Methods for setting, deleting, and listing tags associated with the device. These should be called after a successful channel binding.
```objective-c
+ (void)setTag:(NSString *)tag withCompleteHandler:(BPushCallBack)handler;
+ (void)setTags:(NSArray *)tags withCompleteHandler:(BPushCallBack)handler;
+ (void)delTag:(NSString *)tag withCompleteHandler:(BPushCallBack)handler;
+ (void)listTagsWithCompleteHandler:(BPushCallBack)handler;
```
--------------------------------
### Query Topic List
Source: https://push.baidu.com/doc/python/api
Retrieves a list of used topics and their associated push/ack statistics.
```python
# 查询所用到的分类主题列表,并配合queryTopicRecords查询最近推送过的10条消息
# 消息控制选项
opts = {'limit':10}
c = Channel()
# 发送
try:
# 拿到分类主题列表
ret = c.queryTopicList(opts)
for item in ret['result']:
# 查询推送记录
ret_2 = c.queryTopicRecords(item['topic_id'], opts)
print ret_2
except ChannelException as e:
print e.getLastErrorMsg()
```
--------------------------------
### Configure AndroidManifest for Vendor Proxies
Source: https://push.baidu.com/doc/android/api
Add necessary service and meta-data declarations to your AndroidManifest.xml to enable vendor-specific push proxies like Huawei and VIVO.
```xml
```
--------------------------------
### POST /rest/3.0/push/tags
Source: https://push.baidu.com/doc/restapi/restapi
推送消息或通知给指定的标签。
```APIDOC
## [POST] /rest/3.0/push/tags
### Description
推送消息或通知给指定的标签。
### Method
POST
### Endpoint
/rest/3.0/push/tags
### Parameters
#### Request Body
- **type** (number) - Required - 标签类型(固定为1)
- **tag** (string) - Required - 已创建的tag名称
- **msg_type** (number) - Optional - 消息类型(0:消息, 1:通知)
- **msg** (string) - Required - 消息内容,json格式
- **extra_msg_type** (number) - Optional - 消息类型(0:消息, 1:通知)
- **extra_msg** (string) - Optional - 消息内容,json格式
- **msg_expires** (number) - Optional - 消息过期时间(秒)
- **deploy_status** (number) - Optional - iOS部署状态(1:开发, 2:生产)
- **send_time** (number) - Optional - 定时推送时间
### Response
#### Success Response (200)
- **msg_id** (string) - 该条消息ID
- **timer_id** (string) - 定时任务ID
- **send_time** (number) - 消息的实际推送时间
### Response Example
{
"request_id": 123456789,
"response_params": {
"msg_id": "24234532453245",
"send_time": 1428156644
}
}
```
--------------------------------
### enableHuaweiProxy
Source: https://push.baidu.com/doc/android/api
Configures whether to enable the Huawei proxy mode for push services.
```APIDOC
## public static void enableHuaweiProxy(Context context, boolean proxyEnable)
### Description
Enables or disables the Huawei proxy mode for the push service.
### Parameters
- **context** (Context) - Required - The current execution context.
- **proxyEnable** (boolean) - Required - Whether to enable Huawei proxy mode (default is false).
```
--------------------------------
### iOS 7 后台远程通知处理
Source: https://push.baidu.com/doc/ios/api
用于在后台状态下接收远程通知并执行代码,需在 Xcode 中开启 Remote notifications 功能。
```objective-c
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
```
--------------------------------
### Manage Tags
Source: https://push.baidu.com/doc/android/api
Methods for setting, deleting, and listing tags for targeted push notifications. Tag operations require a successful bind or startWork call.
```java
public static void setTags(Context context, List tags);
```
```java
public static void delTags(Context context, List tags);
```
```java
public static void listTags(Context context);
```
--------------------------------
### Resume Push Service
Source: https://push.baidu.com/doc/android/api
Resumes the Push service and re-performs binding.
```java
public static void resumeWork(Context context);
```