java+uniapp集成unipush2实现消息推送
一、开通uniPush2.01.实名认证登录DCloud开发者中心通过实名认证2.进入UniPush控制台HBuilderX中打开项目的manifest.json文件导航在“App模块配置” → 项的“Push(消息推送)” → “UniPush”下点击配置 或者申请开通。3.配置应用信息在UniPush开通界面配置以下信息Android包名Android应用签名iOS Bundle Id 点击开通完成服务启用详细说明请参考 UniPush开通指南二、前端推送服务对接配置uniCloud服务开通uniCloud服务推荐阿里云创建云函数用于处理推送逻辑详细步骤参考官方文档添加push模块设置targetSdkersiontargetSdkersion过高有些手机运行不了找到刚刚添加的push模块创建云函数处理推送请求云函数关键不要乱写看不懂示例就复制我这个use strict;/** * 推送吃药提醒 - DCloud UniPush 2.0 云函数 */exports.mainasync(event,context){console.log( UniPush云函数被调用 );console.log(请求方法:,event.httpMethod);// 解析请求体letparams;try{if(event.httpMethodPOST){if(typeofevent.bodystringevent.body){paramsJSON.parse(event.body);}elseif(typeofevent.bodyobjectevent.body!null){paramsevent.body;}else{return{code:-1,msg:POST请求体为空或格式错误};}}elseif(event.httpMethodGET){return{code:0,msg:UniPush 云函数运行正常,data:{method:GET,time:Date.now(),tip:请使用 POST 方法发送推送请求}};}else{return{code:-1,msg:不支持的请求方法: event.httpMethod};}}catch(e){console.error(解析请求体失败:,e);return{code:-1,msg:请求体格式错误: e.message};}const{cid,title,content}params;console.log(解析后的参数:,{cid,title,content});// 参数校验if(!cid||!title||!content){console.error(参数不完整);return{code:-1,msg:参数不完整需要: cid, title, content,received:params};}try{console.log(开始初始化UniPush...);// 获取 UniPush 管理器constuniPushuniCloud.getPushManager({appId:__UNI__xxxxxxx// ⚠️ 替换为您的实际 AppID});console.log(UniPush初始化成功开始发送消息...);// 构建推送参数constpushParams{push_clientid:cid,title:title,content:content,payload:{type:medicine_reminder,time:Date.now()},// 添加以下参数确保通知显示force_notification:true,// 强制显示通知栏sound:default,// 提示音badge:1// iOS角标};console.log(推送参数:,JSON.stringify(pushParams));// 发送推送消息constresultawaituniPush.sendMessage(pushParams);console.log(推送结果:,result);// 检查推送结果if(result.errCode0){// 检查具体设备的推送状态constdeviceStatusresult.data?Object.values(result.data)[0]:null;console.log(设备推送状态:,deviceStatus);return{code:0,msg:推送成功,data:result};}else{console.error(推送失败:,result);return{code:-1,msg:推送失败: (result.errMsg||未知错误),detail:result};}}catch(error){console.error(推送异常:,error);return{code:-1,msg:推送异常: error.message};}};传部署云函数代码配置云函数URL化进入uniCloud控制台找到已上传的云函数并查看详情配置云函数url化,设置URL的PATH部分作用是后端直接调接口然后进行推送完成后获得完整URL用于后端调用三、后端推送服务对接packagecom.ruoyi.app.service.impl;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.ruoyi.app.service.IUniPushService;importlombok.extern.slf4j.Slf4j;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.http.*;importorg.springframework.stereotype.Service;importorg.springframework.util.StringUtils;importorg.springframework.web.client.RestTemplate;importjava.util.*;/** * UniPush 2.0 推送服务实现支持Android和iOS * 使用云函数方式调用个推API * * author ruoyi */Slf4jServicepublicclassUniPushServiceImplimplementsIUniPushService{Value(${unipush.cloud-function-url:})privateStringcloudFunctionUrl;privatefinalRestTemplaterestTemplatenewRestTemplate();privatefinalObjectMapperobjectMappernewObjectMapper();/** * 调用云函数发送推送 */privatebooleancallCloudFunction(MapString,ObjectrequestBody){try{if(!StringUtils.hasText(cloudFunctionUrl)){log.error(❌ UniPush云函数地址未配置请在application.yml中配置 unipush.cloud-function-url);returnfalse;}// 打印请求体用于调试StringjsonBodyobjectMapper.writeValueAsString(requestBody);log.info( UniPush云函数请求 - URL: {},cloudFunctionUrl);log.info( UniPush云函数请求体: {},jsonBody);// 发送请求HttpHeadersheadersnewHttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntityStringentitynewHttpEntity(jsonBody,headers);ResponseEntityMapresponserestTemplate.postForEntity(cloudFunctionUrl,entity,Map.class);if(response.getStatusCode()HttpStatus.OKresponse.getBody()!null){MapString,Objectbodyresponse.getBody();log.info( UniPush云函数响应: {},body);// 检查是否是echo响应云函数未正确实现if(body.containsKey(path)body.containsKey(httpMethod)){log.error(❌ 云函数返回了echo响应说明云函数未正确实现推送逻辑);log.error(❌ 请检查云函数代码确保实现了推送功能而不是简单返回请求);returnfalse;}// 判断是否成功 - 支持多种响应格式// 格式1: {code: 0, msg: success}ObjectcodeObjbody.get(code);if(codeObj!null){StringcodecodeObjinstanceofInteger?String.valueOf(codeObj):codeObj.toString();if(0.equals(code)||200.equals(code)){log.info(✅ UniPush推送成功);returntrue;}else{log.error(❌ UniPush推送失败错误码: {}, 消息: {},code,body.get(msg));returnfalse;}}// 格式2: {success: true}ObjectsuccessObjbody.get(success);if(successObjinstanceofBoolean(Boolean)successObj){log.info(✅ UniPush推送成功);returntrue;}// 格式3: {status: success}ObjectstatusObjbody.get(status);if(statusObj!nullsuccess.equalsIgnoreCase(statusObj.toString())){log.info(✅ UniPush推送成功);returntrue;}log.error(❌ UniPush推送失败响应内容: {},body);}else{log.error(❌ UniPush云函数响应异常 - 状态码: {},response.getStatusCode());}returnfalse;}catch(org.springframework.web.client.HttpClientErrorExceptione){log.error(❌ UniPush云函数调用失败 - HTTP状态码: {},e.getStatusCode());log.error(❌ 响应内容: {},e.getResponseBodyAsString());log.error(❌ 请检查);log.error( 1. 云函数URL是否正确: {},cloudFunctionUrl);log.error( 2. 云函数是否已部署并启用HTTP触发器);log.error( 3. 云函数是否正确实现了推送逻辑);returnfalse;}catch(org.springframework.web.client.ResourceAccessExceptione){log.error(❌ UniPush云函数网络访问异常: {},e.getMessage());log.error(❌ 请检查);log.error( 1. 网络连接是否正常);log.error( 2. 云函数地址是否可访问);log.error( 3. 防火墙或代理设置);returnfalse;}catch(Exceptione){log.error(❌ UniPush云函数调用异常,e);returnfalse;}}OverridepublicbooleanpushToSingle(Stringcid,Stringtitle,Stringcontent){try{if(!StringUtils.hasText(cid)){log.warn(推送失败cid为空);returnfalse;}// 构建请求体 - 直接传递参数不使用 action/data 结构MapString,ObjectrequestBodynewjava.util.LinkedHashMap();requestBody.put(cid,cid);requestBody.put(title,title);requestBody.put(content,content);// 调用云函数booleansuccesscallCloudFunction(requestBody);if(success){log.info(单推消息成功cid: {}, title: {},cid,title);}else{log.error(单推消息失败cid: {}, title: {},cid,title);}returnsuccess;}catch(Exceptione){log.error(单推消息异常cid: {}, title: {},cid,title,e);returnfalse;}}OverridepublicbooleanpushToList(ListStringcids,Stringtitle,Stringcontent){try{if(cidsnull||cids.isEmpty()){log.warn(推送失败cid列表为空);returnfalse;}// 注意云函数只支持单个CID推送需要循环调用log.info(批量推送将逐个推送给 {} 个设备,cids.size());intsuccessCount0;for(Stringcid:cids){booleanresultpushToSingle(cid,title,content);if(result){successCount;}// 避免频繁请求间隔100mstry{Thread.sleep(100);}catch(InterruptedExceptione){Thread.currentThread().interrupt();}}booleanallSuccesssuccessCountcids.size();if(allSuccess){log.info(批量推送消息成功数量: {}, title: {},cids.size(),title);}else{log.warn(批量推送部分成功成功: {}/{}, title: {},successCount,cids.size(),title);}returnallSuccess;}catch(Exceptione){log.error(批量推送消息异常title: {},title,e);returnfalse;}}OverridepublicbooleanpushToAll(Stringtitle,Stringcontent){try{log.warn(全量推送功能未实现云函数不支持全量推送);log.warn(如需全量推送请先从数据库获取所有用户的CID然后使用 pushToList 方法);returnfalse;}catch(Exceptione){log.error(全量推送消息异常title: {},title,e);returnfalse;}}}重点发消息需要cidapp获取到传给后端保存cid可能会更新一般登录的时候传。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2604914.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!