记录一下unipush云函数推送
1.云函数-index.js
'use strict';
const uniPush = uniCloud.getPushManager({
appId: "__UNI__56C8C3E"
})
exports.main = async (event) => {
// let obj = JSON.parse(event.body) // 直接调用需要解析。后端调用时,传递的来的数据已经解析成了obj,不需要再转换
let obj = event.body
console.log(obj.cids);
const res = await uniPush.sendMessage({ //云函数中调用uni-cloud-push扩展库的sendMessage方法,向客户端推送消息
"push_clientid": obj.cids, // 设备id,支持多个以数组的形式指定多个设备,如["cid-1","cid-2"],数组长度不大于1000。服务器没有接收到cid,会被认为是群发,而群发是每分钟5次的限制。
"title": obj.title, // 标题
"content": obj.content, // 内容
"payload": obj.data, // 数据
"force_notification": true, // 服务端推送 需要加这一句 。true表示客户端会对在线消息自动创建“通知栏消息”
"request_id": obj.request_id, //请求唯一标识号,10-32位之间;如果request_id重复,会导致消息丢失
"options": obj.options
})
return res //一定要return回去
};
云函数中发请求到后端拿数据
// 云函数中发请求到后端拿数据
'use strict';
const uniPush = uniCloud.getPushManager({
appId: "__UNI__56C8C3E" }); exports.main = async (event) => {
const url = 'http://127.0.0.1:8000/cloud/function/get/data'; // 替换为有效的URL
try {
const res = await uniCloud.httpclient.request(url, {
method: "GET",
dataType: "json"
});
console.log("timingPushGetData--res");
console.log(res);
return await uniPush.sendMessage({
"push_clientid": res.data.cids,
"title": "重庆天气",
"content": res.data.content,
"payload": {
"text": "体验一下uni-push2.0云函数,通过uniCloud.httpclient.request请求url获取数据"
},
"force_notification": true
});
} catch (error) {
console.error("请求数据失败:", error);
// 根据需要处理错误,比如返回一个错误对象给调用者
return { error: "请求数据失败", message: error.message };
} };
发请求获取list数据
'use strict';
const uniPush = uniCloud.getPushManager({
appId: "__UNI__56C8C3E"
});
exports.main = async (event) => {
const networkUrl = 'https://baike.baidu.com/api/openapi/BaikeLemmaCardApi?scope=103&format=json&appid=379020&bk_key=%E9%93%B6%E9%AD%82&bk_length=600'; // 示例URL,实际使用时应替换为有效的URL
const mapingUrl = 'http://kykcje.natappfree.cc/cloud/function/get/dataList';
try {
const res = await uniCloud.httpclient.request(mapingUrl, {
method: "GET",
dataType: "json"
});
const datas = res.data // networkUrl使用 res.data.card
// res需要是一个数组类型的数据,[{},{},.....]返回的数据中包含多个快递状态信息
if (datas || datas.length > 0) {
console.log("timingPushGetData--res");
console.log(datas);
// 循环处理每个快递状态信息
for (let item of datas) {
const pushClientId = item.someUniqueIdField; // 获取cid
// 发送推送消息
await uniPush.sendMessage({
"push_clientid": item.cids,
"title": item.title,
"content": item.content,
"force_notification": true // 一定要开,不开不会推送
});
}
return {success:"响应成功,消息发送完成"}
}
else {
// 如果没有数据或查询无结果
return { nodata: "没有查询到数据" };
}
}
catch (error) {
return { error: "请求数据失败", message: error.message };
}
};
2.app.vue
// 获取 cId 可以理解为设备id
uni.getPushClientId({
success: (res) => {
console.log(res.cid);
},
fail: (res) => {
console.log(res);
}
});
//获取透传消息
uni.onPushMessage(res=>{
console.log(res)
// 下拉通知栏展示消息
if(res.type == "receive"){
uni.createPushMessage({
title:"你有新的消息,请注意查收",
content:res.data.payload.name,
payload:res.data.payload.name
})
}else if(res.type == "click"){
console.log(res)
uni.navigateTo({
url:"/pages/demo/demo?id="+res.data.payload.id
})
}
console.log("res.data.payload.name")
console.log(res.data.payload.name)
});
//App.vue中注册以下两个事件,app端集成消息推送就完成了,在后台或者开发者中心,进行消息推送就可以收到推送的消息
//点击通知消息时,执行该事件
plus.push.addEventListener("click",function(message){
//自定义内容获取
let payload = message.payload;
//解析自定义内容
try{
//完成业务逻辑
}
catch(e){
}
});
//收到透传消息时,执行该事件
plus.push.addEventListener("receive",function(message){
//自定义内容获取
let payload = message.payload;
//解析自定义内容
try{
//完成业务逻辑
}
catch(e){
}
});
//云函数相关
uni.getPushClientId({
success: (res) => {
let push_clientid = res.cid;
console.log('客户端推送标识cid:', push_clientid);
},
fail(err) {
console.log(err);
}
})
//#ifdef APP-PLUS
var info = plus.push.getClientInfo()
// 使用5+App的方式进行监听消息推送
plus.push.addEventListener("click", function(msg) {
console.log("click:" + JSON.stringify(msg));
console.log(msg.payload);
console.log(JSON.stringify(msg));
// onLaunch 生命周期里,页面跳转有问题,跳不过去
// 应该是页面还没加载,加上定时后,就可以了;
setTimeout(() => {
// uni.navigateTo({
// url: `packageA/pages/order-detail/order-detail?orderId=${msg.payload.orderId}`
// })
}, 1000)
}, false);
// 监听在线消息事件
plus.push.addEventListener("receive", function(msg) {
//业务代码
console.log("recevice:" + JSON.stringify(msg))
if ("LocalMSG" == msg.payload) {} else {
if (msg.type == 'receive') {
var options = {
cover: false,
title: msg.title
};
plus.push.createMessage(msg.content, msg.payload, options);
}
}
}, false);
//#endif
3.前端调用云函数
uniCloud.callFunction({
name:'pushTest',
data: {
body:{
"cids": "bedc8d5c7ac62044c00b3a378804c050",
"title": "今日天气",
"content": "晴,温度适中,适合出去玩",
"data": {
data1: 1,
data2: 2
}// 注意这里需要序列化 data 对象
}
},
success: function(res) {
// 调用成功
console.log('云函数调用成功:', res.result);
},
fail: function(err) {
// 调用失败
console.error('云函数调用失败:', err);
}
})
4.java后端调用云函数
package com.example.project.unipush2;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
public class UniPushTest {
public static void main(String[] args) {
// 目标URL
String url = "云函数的url";
// 创建JSON数据
ObjectMapper objectMapper = new ObjectMapper();
try {
String jsonData = objectMapper.writeValueAsString(new DataEntity(
"自己的cid",
"title",
"content"
));
// 创建HttpClient实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost实例
HttpPost httpPost = new HttpPost(url);
// 设置请求头,指定发送的数据类型为JSON
httpPost.setHeader("Content-type", "application/json");
// 设置请求体
StringEntity entity = new StringEntity(jsonData, ContentType.APPLICATION_JSON.withCharset("UTF-8"));
httpPost.setEntity(entity);
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
// 读取响应内容
try {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
String result = EntityUtils.toString(responseEntity);
System.out.println(result);
}
} finally {
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
5.实体类
import lombok.Data;
@Data
public class DataEntity {
// cid
private String cids;
private String title;
private String content;
public DataEntity(String cids, String title, String content) {
this.cids = cids;
this.title = title;
this.content = content;
}
}