提示

本文为uni-push 2.0(需要HBuilderX 3.5.1 及其以上版本支持)的介绍,如果旧项目需要使用老版本的uni-push 1.0,另见:uni-push 1.0

# uni-push介绍

查看uni-push介绍

# 概述

uni-push 2.0是DCloud推出的、全端的、云端一体的统一推送服务。

  1. 客户端方面,uni-push 2.0支持App、web、小程序。

    • App端,内置了苹果、华为、小米、OPPO、VIVO、魅族、谷歌FCM等手机厂商的系统推送和个推第三方推送
    • 小程序端,内置了socket在线推送。如需模板消息/订阅消息,另见uni-subscribemsg
    • web端,内置了socket在线推送 (uni-push1仅支持app,且app必须包含个推原生sdk。uni-push2在app端如不需要厂商推送,只需在线推送,无需集成个推原生sdk)
  2. 服务端方面,uni-push 2.0支持uniCloud云端一体,无需再编写复杂代码轻松完成push。 (uni-push1.0仅支持使用传统服务器开发语言如php,未和客户端有效协同,流程比uni-push2.0繁琐)

  3. uni-push also comes with a web console. You can also send pushes on web pages without writing code. The web console of uni-push1.0 is at dev.dcloud.net.cn. The web console of uni-push2.0 is open source and belongs to the uni-admin plugin see details.

  4. 如果你的项目由于特殊原因不能通过uniCloud的云函数使用uni-push2.0,你希望直接通过调用个推服务器推送消息。在这种情况下:

    • uni-app项目,需要使用老版的 uni-push1.0 。相关密钥获取方式:登录开发者中心左侧菜单->uni-push->uni-push 2.0(支持全端推送)->消息推送->应用配置->应用信息
    • uni-app-x 项目,虽然只能使用 uni-push2.0,但支持在开发者中心左侧菜单-uni-push->uni-push 2.0(支持全端推送)-> 厂商推送设置 在顶端注意事项中,点击获取个推的MasterSecret

请注意,直接调用个推服务器进行推送可能需要更多的配置和操作步骤,具体请参考调用个推服务器的相关文档。

# 为什么选择uni-push 2.0

Due to the large number of mobile phone manufacturers, they each have different push services, including Apple, Google (only available overseas), Huawei, Xiaomi, oppo, vivo, Meizu, and some small and medium-sized mobile phone brands that do not have professional push services. They have a mechanism to check and kill the power consumption of the app in the background. Except for WeChat and other large applications, it is difficult for ordinary applications to stay in the background.

It would be too difficult for developers to connect the client and server SDKs of each of the above platforms and deal with small and medium-sized mobile phones without push services by themselves. Therefore, there are professional push service providers in the industry that encapsulate the channels of various mobile phone manufacturers into a set of unified API, such as Ge Push (which belongs to the daily interaction of listed companies); at the same time, these three-party professional push providers also provide high-speed socket channels. When the application is online, it can also send messages directly through the socket. Otherwise, developers need to write a lot of judgment code, build a socket server, and deal with various differences between online and offline.

DCloud与个推(A股上市公司每日互动)深度合作,为uni-app的开发者提供了比传统方案便利甚多的统一推送方案uni-push 2.0,利用云端一体的优势,同时提供基于uniCloud的push服务器和基于uni-app的push客户端,两者高效协同,极大的简化了push的使用。

Note: The server stability of uni-push is guaranteed by Alibaba Cloud serverless, Tencent Cloud serverless, and Getui, all of which are listed companies with over 100 million daily active users, so there is no need to worry about stability.

如下图所示: 首先开发者的uniCloud应用服务器向uni-push服务器发送push消息,然后

  • If the client application is online, the client directly receives the push online message through the socket;
  • 客户端应用不联网时,uni-push服务器根据客户端类型,把push消息发给某个手机厂商的push服务器或小程序的订阅消息服务器;然后厂商push通道会把这条消息发到手机的通知栏或微信的订阅消息里;手机用户点击通知栏消息或小程序订阅消息后,启动App或小程序,客户端才能收到离线消息。 img

Summarize the functions provided by uni-push:

  1. An online socket downlink service, regardless of app, applet, or web, as long as it is online, it can push messages from the server. Especially for uniCloud users, this free socket downlink service has many uses.
  2. The app platform provides push when the app is offline, and aggregates the push channels of all known mobile phone manufacturers; for small mobile phone manufacturers that do not provide push channels, it provides background resident processes to receive push messages (subject to mobile phone rom power saving settings)
  3. The Mini Program platform currently provides downlink socket channels, and will integrate the subscription messages when the Mini Program is offline in the future
  4. The web platform currently provides downlink socket channels, and will provide webnotification encapsulation in the future. When the tab is stuck in the background (note not closed), the notification bar can still pop up on the screen.
  5. 快应用平台,目前提供了下行socket通道,后续会提供离线push的封装
  6. 一个uni-admin插件,开源的web控制台,无需编程,可视化界面发送push消息 详见

uni-starter里,还提供了app push权限判断、申请、开关设置,搭配使用可以大量降低开发工作量。

Note: The operating system or browser will automatically pop up a window to ask the user whether to agree or not. Under the applet, the mobile phone user needs to actively initiate the subscription behavior before the message can be delivered.

uni-push not only reduces the development cost, but also improves the push delivery rate. It also supports all platforms and is free. It is the best solution for current push.

# uni-push 2.0 使用uniCloud产生的费用说明

uni-push 2.0本身并不收费,实际使用中需要依赖uniCloud云服务,而uniCloud价格很实惠:

  • It only costs 0.0133 yuan to call cloud functions 10,000 times
  • It only costs 0.015 yuan to call 10,000 database queries

It can be seen that the price is so low that it is almost negligible.

一次消息推送 = 1次云函数请求 + 最高3次数据库查询(最常用的基于user_id推送仅需一次查询,详情参考:推送接口查库详解

即:最高(1 * 0.0133 + 3 * 0.015)/10000 = 0.00000583元/每次(注:给你的应用的所有注册用户群发消息算一次)

详细的计费参考:阿里云版uniCloud按量计费文档

# 快速上手

# 第一步:开通

查看开通文档

# 第二步:配置

  • iOS 平台如需要使用推送功能,还需要上传专用的推送证书
  • Android 平台如需要使用离线推送,需要配置APP手机厂商推送参数(可选,应用进程离线时推送通道)

以上配置,详见:uni-push其它配置

# 第三步:客户端操作

# 名词解释

# 离线推送

It is only supported on the APP side. When the application is closed by the user or runs in the background, the mobile phone manufacturer will terminate the APP background networking in order to save power or release memory.

The message will be sent to the mobile phone system push service module through the mobile phone manufacturer channel that will not be offline;

At this time, the client will automatically create a notification bar message and display it in the system message center (as shown in the figure), but the client cannot monitor the content of the message; when the user clicks the notification bar message, the APP will wake up and the APP can only monitor the message. content.

# 在线推送

When the application is online, no "notification bar message" will be created, and the client will immediately monitor the content of the message.

如果你希望当应用在线时,也通过“通知栏消息”来提醒用户;可以通过以下两种方式实现:

  1. 监听到消息内容后,根据业务需要自己判断是否要创建“通知栏消息”,需要就调用创建本地消息API uni.createPushMessage(uni-app 框架详情参考,uni-app x 框架详情参考) 手动创建通知栏消息。
  2. When the server executes the push, pass the parameter force_notification:true, and the client will automatically create a "notification bar message" (you cannot listen to the message content at this time). When the user clicks the notification bar message, the APP can listen to it. Message content.

The above two solutions have their own advantages and disadvantages, and the first solution is more flexible; for example, in the customer service function, when the client receives a chat message, if the application has already opened the chat dialog page, it will directly render the monitored push content to the page. If the app does not open the chat page, call the api to create a "notification bar message" to remind the user; at this time, you can also perform some other logic, such as adding a red dot to the message center of the tabBar. Option 2 is relatively simple. The client does not need to write additional code to automatically create notification bar messages; but it is only suitable for scenarios where "notification bar messages" are created without caring about client behavior, such as the push of advertising and marketing content.

# 客户端类型

个推的客户端类型是仅根据使用的sdk类型来判断的,分为两类:

  1. native sdk(在manifest.json->APP 模块配置->uniPush 2.0配置界面勾选离线推送时启用的 sdk),获取到的 cid 的 phoneType 为 APP 类型。
  2. jssdk(manifest.json->APP 模块配置->uniPush 2.0配置界面,仅勾选在线推送,未勾选离线推送时启用的 sdk),获取到的 cid 的 phoneType 均为小程序,而不管实际上你的客户端是 APP、小程序还是 web。

# 客户端启用uni-push2.0

# uni-app x 框架的App端

标准基座不包含uni-push模块,如果需要使用此模块,应当在提交云打包时,项目代码中包含uni-push相关客户端api。点此了解uni-app x的摇树机制

所以在开发调试时,需要先写一段包含uni-push相关客户端api代码,再打一个自定义基座。

例如:

  1. 先添加如下代码:
uni.getPushClientId({
  success(res) {
    console.log(res);
  },
  fail(err) {
    console.log(err)
  }
})

注意:此时由于运行的标准基座中,不包含uni-push模块,如果运行会报错,不用着急继续往下操作

  1. 点击菜单栏的【发行】-【原生APP-云打包】然后再弹出的窗口中勾选【制作自定义调试基座】- 点击【打包】
  2. 打包成功后,点击菜单栏的【运行】-【运行到手机或模拟器】-【运行到 Android App 基座】然后再弹出的窗口中勾选【使用自定义基座运行】-【运行】

接下来即可使用 uni-push 相关客户端 api

# uni-app 框架App端

# h5端

# 微信小程序端

Refer to WeChat Mini Programs for other ways of enabling small programs, which will not be listed here.

After configuring in manifest.json, you need to recompile the project, that is: click the Rerun button as shown in the figure

# 小程序中使用uni-push2.0的白名单配置

uni-push is a websocket on the web and applet side; each applet platform requires the configuration of the network server domain name of the applet application in the applet management background, otherwise it will not be able to connect to the Internet.

According to the following table, set the socket legal domain name in the applet management background. The domain names in the table below are all self-owned domain names, not the domain names of DCloud.

  • Versions below HBuilderX 3.6.15 (the connection between the MiniApp and the web-side WebSocket is unstable, please upgrade as soon as possible)
Domain Name Port
wshz.getui.net 5223
wshz.gepush.com 5223
  • HBuilderX 3.6.15 and above
Domain Name Port
wshzn.gepush.com 5223
wshzn.getui.net 5223(3.8.5新增)

# 客户端监听推送消息

The code that listens for push messages needs to be executed before receiving push messages. So it should be written in the application lifecycleonLaunch that will be triggered as soon as the application starts.

示例代码:

// 文件路径:项目根目录App.vue/uvue
export default {
	onLaunch: function() {
		console.log('App Launch')
		uni.onPushMessage((res) => {
		})
	},
	onShow: function() {
		console.log('App Show')
	},
	onHide: function() {
		console.log('App Hide')
	}
}

先跟着示例代码简单体验,详细的uni.onPushMessage API介绍:uni-app 框架详情参考,uni-app x 框架详情参考

APP端真机运行注意:

  • 如果启用了离线推送,必须:经过发行原生app云打包后,客户端才能监听到推送消息。标准HBuilder运行基座无法使用。
  • If the Android app enters the background (the App is not destroyed), and the app cannot be launched by clicking the notification message, please check whether the device has a pop-up interface that prohibits the background. Path >> Settings - Application Management - Test Application - Permission Management - Background pop-up interface, ( Usually millet, oppo, vivo devices).

# 获取客户端推送标识

If I want to call "Zhang San", I need to know the phone ID of the other party, that is, what the phone number is. Similarly, to push a message to a client, you also need to know the client push identifier of the device.

先跟着示例代码简单体验,详细的uni.getPushClientId API介绍:uni-app 框架详情参考,uni-app x 框架详情参考 Code example:

// uni-app client gets push client tag
uni.getPushClientId({
	success: (res) => {
		let push_clientid = res.cid
	},
	fail(err) {
		console.log(err)
	}
})

# 第四步:服务端推送消息

Message push is a sensitive operation that can only be triggered directly or indirectly by the server. The traditional three-party push service requires the developer to configure a key or certificate on the server side, obtain the token according to the server-side document signature, and then initiate a network request to the relevant URL interface...

而uni-push2.0,开发者无需关心证书、签名、服务器端文档,使用简单。云函数通过 uni-push服务端sdk,即uni-cloud-push的API即可直接执行uni-push所有操作。

The server-side SDK of uni-push is not small in size, and it is not built into the cloud function. In cloud functions that need to operate uni-push, developers need to manually configure the uni-cloud-push extension library. (uniCloud extension library, which is not commonly used in uniCloud's own API and has a large package size, is an independent extension library, and developers can choose whether to use this extension library)

  • When creating a new cloud function in HBuilderX, you can choose the uni-cloud-push extension library, or right-click on the existing cloud function directory as shown in the figure below and select "Manage Common Module or Extension Library Dependencies"

The following is a package.json example of a cloud function with the uni-cloud-push extension library enabled. Note that there should be no comments. The comments in the following file content are for illustration only. If you copy this file, remember to remove the comments

{
	"name": "test",
	"version": "1.0.0",
	"description": "",
	"main": "index.js",
	"extensions": {
	},
	"author": ""
}

**Note: The extension library depends on 3 opendb tables: opendb-tempdata, opendb-device, uni-id-device. In the public beta version of uniCloud, the execution extension library will be automatically created. If you are using the official version of uniCloud, you need to create these 3 tables yourself. **

Call the sendMessage method of the uni-cloud-push extension library in the cloud function to push messages to the client

// simple usage example
'use strict';
exports.main = async (event, context) => {
	return await uniPush.sendMessage({
		"push_clientid": "xxx", 	//填写上一步在uni-app客户端获取到的客户端推送标识push_clientid
		"title": "通知栏显示的标题",	
		"payload": {
		}
	})
};

在云函数文件目录右键(或按快捷键ctrl + r)-> 运行-本地云函数,此时你的客户端将收到推送消息(应用关闭时为通知栏消息,在线时代码监听到推送消息)

先跟着示例代码简单体验一下,详细的uniPush.sendMessage API介绍详情参考

If the steps are completed, the uni-app client you run at this time will print out "Push message received: xxxx". In case of exception, you can run it again.

# 最佳实践

上一节,演示了基于“客户端推送标识”的消息推送,仅为方便理解和体验;在业务开发中,通常是指定消息的接收人,而不是某个设备。

如果项目使用uni-id-pagesuni-id-pages-x,即可直接指定基于uni-id的user_id、user_tag,并可筛选设备的平台、登录信息是否有效等,执行推送消息。

uni-id-pages/uni-id-pages-x 已经内置了:在登录账号、退出账号、切换账号、token续期、注销账号5个时机,管理uni-id-device表、opendb-device表与user_id、push_clientid、platform、os_name等字段的映射关系。详情参考

注意

以上内置逻辑,在uni-id-pages下,会自动判断是否启用push模块自动执行;但uni-id-pages-x下,需手动在:/uni_modules/uni-id-pages-x/init.uts导入 autoReportPushClientId 模块。

此外uni-push 2.0 还提供了uni-admin中的web控制台uni-push-admin。包含消息推送、推送统计等功能,而且是开源的,可自定义。如图:

# 常见问题

参考文档

使用有其他疑问,欢迎扫码加入 uni-push2.0 微信交流群讨论: