# uni-push2统一推送

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

# 应用场景

以下功能可以用uni-push 实现

  • 用户消息通知
    When the relevant status of APP users or the status of system functions changes (such as user order notifications, transaction reminders, logistics notifications, upgrade reminders, social interaction reminders, etc.), users can be notified in time, or users can be prompted to complete specific operations.

  • 离线语音播报
    It is also a user message push, the implementation principle is actually to customize the notification reminder ringtone

  • 营销促活通知
    In daily marketing promotion, promotional activities and other scenarios (such as the Double 11 promotion, new product launches, important information, etc.), the APP can send targeted notifications to target users + push in-app messages to attract users to participate in activities and improve daily activities.

  • 基于uniCloud的IM、聊天、客服、棋牌游戏交互等
    例如:DCloud基于uni-push2开发并开源了uni-im详情:https://doc.dcloud.net.cn/uniCloud/uni-im.html
    In addition, chess and card games and other requirements that require the client to passively receive messages can be implemented with uni-push.

# Introduction

# 概述

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

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

  2. 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.

  3. 如果你的项目由于特殊原因不能通过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

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

# What is push?

Push refers to the technology in which the server actively sends messages to the client. Instant data is available without the need for the client to continuously poll the server.

Polling has many disadvantages: 1) The client application must be online in real time; 2) The mobile phone consumes a lot of power; 3) The server load is high and wastes resources

The notification bar of the mobile phone and the subscription message of the applet are all a kind of push. The mobile operating system or WeChat provides a push channel at the bottom layer, which shields various drawbacks of polling. Your application can be closed, as long as the mobile phone has a network, the push channel provided by the operating system is online in real time.

Reminder: The webnotification of the web browser is actually a local notification bar function, and the browser manufacturer does not provide a push channel.

When the client is online, push is implemented through the socket protocol. When the client is offline, the server cannot find the client, and the developer cannot implement the push by himself. He can only rely on the offline message push provided by the mobile phone operating system and the bottom layer of the applet, and call the server interface of the designated mobile phone manufacturer or applet manufacturer to send the message. information.

Therefore, a push system needs three parts of cooperation: the developer's business server + the professional push server + the developer's client application.

Its main process is:

  1. The developer's business server sends instructions to the professional push server, informing which clients need to send what kind of messages
  2. The professional push server sends a message to the client
  3. If the mobile application is online, it will receive the push directly; if it is not online, the mobile phone user will see the push message in the notification bar of the operating system, click it to call up the client application, and the client code can receive the response and get the message; if it is a small If you are a program, you will see the subscription message in the WeChat message, click it to call up the applet and get the startup parameters.

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-push2,利用云端一体的优势,同时提供基于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或小程序,客户端才能收到离线消息。

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-push2.0 Description of the cost generated by using uniCloud

uni-push本身并不收费,实际使用中需要依赖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按量计费文档

# common problem

With uni-push, developers should no longer use other push schemes. However, we found that many developers have misunderstandings, which lead to the wrong use of other pushes.

  • Common misunderstanding 1: "Is the professionalism of uni-push comparable to professional personal push, Aurora and other services?"

    答:uni-push 是由个推将其本来收费的 push 产品,免费提供给了DCloud的开发者。它与个推vip push的只有3个区别:1、免费;2、账户使用的是DCloud开发者账户,而无需再重新注册个推账户;3、开发文档看DCloud的。

  • Common misunderstanding 2: "uni-push is so troublesome, I like simple sdk like push and aurora, and I don't want to go to various rom manufacturers to apply for a circle"

    A: uni-push is not based on applying for authorization from mobile phone manufacturers. If you do not apply for those, it will be the same as using ordinary push. However, special attention should be paid to the status quo of the push industry: without integrating the push of the rom manufacturer, it is impossible to send push when the app is offline. According to the normal push mode, the consequence is that offline messages cannot be sent on Huawei, Xiaomi, OPPO, VIVO, and Meizu.

  • Common misunderstanding 3: "Is the delivery rate of uni-push high? Is it possible to pay to increase the delivery rate? There is a way to pay to increase the delivery rate of uni-push"

    A: It has been mentioned above. The paid product of uni-push to improve the delivery rate is vip push, and uni-push is the vip push of uni-push. DCloud has been negotiated for free use by DCloud developers.

  • Can uni-push completely replace sockets?

    答:能部分替代。uni-push客户端接收消息的通讯协议属于websocket;但业务服务端向uni-push服务发送消息用的是http通讯协议,会有1-2秒的延时。需要超低延迟的应用场景,如多人交互远程画板不合适。但对于普通的im消息、聊天、通知都没有问题。

  • 5+app和wap2app支持uni-push2.0吗?

    A: Not currently supported.

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

# 快速上手

# 第一步:开通

  • 使用 HBuilder 账号登录 开发者中心
  • 在左侧菜单栏找到uni-push-uni-push 2.0(支持全端推送)-应用信息,点击“当前应用”选择要操作的应用。

# Phone number verification

According to national legal requirements, all companies that provide cloud services need to verify mobile phone numbers when users use cloud services.

# Fill in the application information

Description of associated service space: uni-push2.0 requires developers to activate uniCloud. It doesn't matter if your business server uses uniCloud or not, but the professional push server is on uniCloud.

  • If your backend business is developed using uniCloud, it is easier to understand.
  • If your background business does not use uniCloud, you also need to create an uniCloud environment in the uni-app project, bind the same service space in HBuilderX and the uni-push configuration of dev, and the previous business is still connected by the client. There are traditional servers, and push-related functions are implemented through the uniCloud service space. If you have used the three-party push service before, it can be understood that your server no longer calls the personal push server, but instead calls the uniCloud service space.

In the cloud function of uniCloud, load the extension library uni-cloud-push, and directly call the related API without additional server configuration. Traditional server developers need to convert this cloud function URL into an http interface, and then call this http interface from the original php or java code.

Note: The Android package name, signature (SHA1 fingerprint) or iOS Bundle ID must be consistent with the certificate-related information configured in the manifest.json of the client, otherwise, the package may not be properly packaged or the push message may not be received.

Reference materials: About Android certificate, iOS certificate application

After the activation is completed, you can still modify the above information here.

There are many complete processes for opening an app, but the process for opening a web and a small program is relatively simple, and it can be used immediately. A uni-app project can be quickly run into a browser or applet experience.

# 第二步:配置

  • iOS platform also needs to upload a dedicated push certificate
    • Certificate application: how to obtain the push certificate, please refer to the official document tutorial iOS certificate configuration guide
    • Certificate upload entry: message push - "configuration management" - "application configuration"
  • APP mobile phone manufacturer push parameter settings (optional, push channel when the application process is offline) uni-push集成并统一了各个手机厂商的系统级推送,目前支持魅族、OPPO、华为、小米、VIVO。如果需要使用厂商推送,需要先在各厂商开发者平台申请。详见厂商推送应用创建配置流程

# Step 3: Client Operation

# Glossary

# 离线推送

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.

# Online push

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

# Whitelist configuration

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) => {
			console.log("收到推送消息:",res) //监听推送消息
		})
	},
	onShow: function() {
		console.log('App Show')
	},
	onHide: function() {
		console.log('App Hide')
	}
}

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

APP端真机运行注意:

  • 如果启用了离线推送,必须:经过发行原生app云打包后,客户端才能监听到推送消息。标准HBuilder运行基座无法使用。
  • 离线推送时,Android手机厂商通道推送需设置消息渠道id,否则会被限制频次和静默推送(静音且需下拉系统通知栏才可见)
  • 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
		console.log('客户端推送标识:',push_clientid)
	},
	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": {
		"uni-cloud-push": {} // 配置为此云函数开启uni-cloud-push扩展库,值为空对象留作后续追加参数,暂无内容
	},
	"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';
const uniPush = uniCloud.getPushManager({appId:"__UNI__XXXXXX"}) //注意这里需要传入你的应用appId,用于指定接收消息的客户端
exports.main = async (event, context) => {
	return await uniPush.sendMessage({
		"push_clientid": "xxx", 	//填写上一步在uni-app客户端获取到的客户端推送标识push_clientid
		"title": "通知栏显示的标题",	
		"content": "通知栏显示的内容",
		"payload": {
			"text":"体验一下uni-push2.0"
		}
	})
};

在云函数文件目录右键(或按快捷键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.

# Best Practices

In the previous chapter, the message push based on the "client push identity" was demonstrated, which is only for the convenience of understanding and experience; in business development, the recipient of the message is usually specified, not a certain device.

如果项目使用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-push2.0 还提供了uni-admin中的web控制台uni-push-admin。包含消息推送、推送统计等功能,而且是开源的,可自定义。如图: