uniapp提供了unipush统一推送服务,但是每次要推送消息的时候都要登陆Dcloud开发者后台,有点不方便,运营需要在我们的后台系统就可以完成操作。
如何使用Dcloud的uniPush
unipush
官方对于unipush的基础使用描述得十分详细, 但是需要对接离线推送,需要去各个厂商申请,不然只能在线推送
个推对接
我这里不考虑离线消息,在线的消息测试基本都成功, 由于单推要cid, 要修改代码获取cid, 这里直接以群推为例
我对接的是个推的RestAPI V2
- app端
// 这段代码是获取cid的,当时打包的时候没有写这个,目前先要对接个群推先用一下, 可以在用户每次进入设备的时候先拿到,存到数据库
const pinf = plus.push.getClientInfo()
const cid = pinf.clientid
console.log(`cid=${cid}`)
// 监听push推送通知
plus.push.addEventListener('receive', msg => {
this.globalData.test1 = JSON.stringify(msg)
})
// 监听点击通知栏
plus.push.addEventListener('click', msg => {
this.globalData.test2 = JSON.stringify(msg)
})
- 服务端:获取token
async getGeTuiToken() {
const { ctx } = this
const { appId, appKey, appSecret, masterSecret } = accounts.appPush
const timestamp = Date.now()
const sign = crypto.createHash('sha256').update(`${appKey}${timestamp}${masterSecret}`).digest('hex')
const res = await ctx.curl(`${baseUrl}${appId}/auth`, {
method: 'POST',
contentType: 'json',
data: {
sign,
timestamp,
appkey: appKey
},
dataType: 'json'
});
return res.data.data
}
- 服务端:群推
async toApp() {
const { ctx, app, service } = this
const { appId } = accounts.appPush
let token = await service.cache.get('getui_token')
if (!token) {
token = await service.push.getGeTuiToken()
}
const { title, body_msg, big_text, click_type, payload } = ctx.request.body
console.log(title, body_msg, big_text, click_type, payload)
// 这判断是不正确的,因为click_type决定payload
if (!title || !body_msg || !click_type) return ctx.body = '参数不正确'
const result = await ctx.curl(`${baseUrl}${appId}/push/all`, {
method: 'POST',
contentType: 'json',
dataType: 'json',
data: {
request_id: 'june' + Date.now() + 'push',
audience: 'all',
push_message: {
notification: {
title,
body: body_msg,
big_text,
channel_level: 3,
click_type: 'payload',
payload
}
},
push_channel: {
android: {
ups: {
notification: {
title,
body: body_msg,
click_type: 'payload',
payload
}
}
}
}
},
headers: {
token
}
});
ctx.body = result
}
END
这个是我测试用的代码,群推只需要关注controller/common/push.js的toApp
这个仓库为测试用的,有oss,cos,微信支付,分享签名,需要在config目录下填写一些账号
module.exports = {
wechat: { // 公众号
appId: '',
appSecret: '',
token: '',
baseUrl: ''
},
wechatMini: { // 小程序
appId: '',
appSecret: ''
},
wetchatApp: { // app
appId: '',
appSecret: ''
},
wechatPay: { // 商户号
MCHID: '',
key: '' // 商户号api密钥
},
appPush: { // app推送
appId: '',
appKey: '',
appSecret: '',
masterSecret: ''
},
tx: { // 腾讯云
appId: '',
secretId: '',
secretKey: ''
},
tx_cos: { // 腾讯cos
bucket: '',
region: ''
},
ali_oss: {
accessKeyId: '',
accessKeySecret: '',
bucket: '',
endpoint: ''
}
}