java - uniapp集成uni-push1.0

2024-01-02 09:23:14

uni-push1.0官方文档:https://uniapp.dcloud.net.cn/unipush-v1.html

uniapp开通uni-push官方教程: https://ask.dcloud.net.cn/article/35716

uniapp多厂商通道配置流程教程: https://uniapp.dcloud.net.cn/unipush_vendor_config.html

个推多厂商通道配置流程教程:https://docs.getui.com/getui/mobile/vendor/vendor_open/

个推API文档:https://docs.getui.com/getui/

☆注意☆

详细请通过以上链接学习,以下仅供集成例子参考

userId(uid)和clientId(cid) 持久化代码没有给全之外,其余全部都可直接拿来学习!!

一、uni-push简介

unipush是DCloud 和个推公司集成的统一推送服务,内建了苹果、华为、小米、OPPO、VIVO、魅族、谷歌 FCM 等手机厂商的系统级推送和个推等第三方推送。

推送流程图–官方图

在这里插入图片描述

二、uniapp端

uni-push.js–相关工具方法

此处给出工具方法,后面再APP.vue中使用

import {getBrageNum} from '@/api/read/read.js';
export default {

	handlePushMessage(msg,type) {
		/*
		这里是在线接收消息处理逻辑
		*/
		// #ifdef APP-PLUS
		if(type === 'receive'){
			// console.log(msg,"在线事件")
			if (plus.os.name=='iOS') {  //由于IOS 必须要创建本地消息 所以做这个判断
				if (msg.payload&& msg.payload!=null) {
					// console.log(msg);
					const options={
						cover:false,
						sound:"system",
						title:msg.title,
						
					}
					// {"title": "xxx","content": "xxx","payload": "xxx"} 符合这种 才会自动创建消息  文档地址https://ask.dcloud.net.cn/article/35622
					plus.push.createMessage(msg.content,JSON.stringify(msg.payload),options)  //创建本地消息
				}
			}
			if (plus.os.name=='Android') {
				// console.log('安卓处理')
				const options={
					cover:false,
					sound:"system",
					title:msg.title,
					icon:'/static/images/logo.png'
				}
				plus.push.createMessage(msg.content,msg.payload,options);
				}
		}
		/**
		 * 这里可能是跳转到某个页面等操作,请根据自身业务需求编写。  
		 */  
		else{
			
			}
		}
		// #endif
	},
    /**
    * 获取clientid
    */
	getClient: (callback) => {
		// #ifdef APP-PLUS
		let clientid = '';
		var timer = setInterval(() =>{
			let clientInfo = plus.push.getClientInfo();  //获取 clientID
			// console.log(clientInfo.clientid,'clientId')
			clientid = clientInfo.clientid;
			if(clientInfo&&clientid != "null"){
				uni.setStorageSync('clientid', clientid);
				clearInterval(timer);
			}
		},50)
		// #endif
 
	},
        /**
        * 设置角标
        */
	setBladeNumber(){
		// #ifdef APP-PLUS
        //后端请求回来的角标数据
		getBrageNum().then(res =>{
			const num = Number(res.data);
			plus.runtime.setBadgeNumber(isNaN(num) ? 0 : num);
		})
		// #endif
		
		
	},
    /**
     * 判断是否为空
     */
     validatenull(val) {
        if (typeof val == 'boolean') {
            return false;
        }
        if (typeof val == 'number') {
            return false;
        }
        if (val instanceof Array) {
            if (val.length == 0) return true;
        } else if (val instanceof Object) {
            if (JSON.stringify(val) === '{}') return true;
        } else {
            if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '')
            {	return 	true;	}
            
            return false;
        }
        return false;
    }
	
}

实现

在uniapp项目中的APP.vue的onLunch方法

<script>
	import unipush from "@/utils/unipush/uni-push.js";
	export default {
		data() {
			return {
			}
		},
		onLaunch: function() {
		
			console.log('App Launch')
            //获取cilientId  唯一推送cid
			unipush.getClient(); 
			// #ifdef APP-PLUS
			unipush.setBladeNumber();
			plus.push.setAutoNotification(false); //设置为false 方便自己处理系统消息,否则自动添加到系统消息列表上去
			//点击通知
			plus.push.addEventListener('click', function(message) {  
				unipush.handlePushMessage(message,"click");  //工具方法里面的统一处理消息
			});  
			//在线消息捕获 
			plus.push.addEventListener('receive', function(message) {  
				unipush.handlePushMessage(message,"receive");  //工具方法里面的统一处理消息
			});  
			// #endif
		},
		onShow: function() {

		},
		onHide: function() {
			console.log('App Hide')
		},
	
    },
		methods: {
			
		}
	}
</script>
<style lang="scss">
	
</style>

三、java集成推送restfulAPI

☆☆☆

在线: ios不支持通知类型 所以都是用透传 离线: 安卓只有华为能用透传 所以都使用通知类型

消息模板

{
    "request_id": "请填写10到32位的id",
    "audience": {
        "cid": [
            "请输入clientid"
        ]
    },
    "settings": {
        "ttl": 3600000,
        "strategy": {
            "default": 1
        }
    },
    "push_message": {
        //此格式的透传消息由 unipush 做了特殊处理,会自动展示通知栏。开发者也可自定义其它格式,在客户端自己处理。
        "transmission": "{title:\"标题\",content:\"内容\",payload:\"自定义数据\"}"
    },
    "push_channel": {
        "android": {
            "ups": {
                "notification": {
                    "title": "安卓离线展示的标题",
                    "body": "安卓离线展示的内容",
                    "click_type": "intent",
                    //注意:intent参数必须按下方文档(特殊参数说明)要求的固定格式传值,intent错误会导致客户端无法收到消息
                    "intent": "请填写固定格式的intent"
                }
            }
        },
        "ios": {
            "type": "notify",
            "payload": "自定义消息",
            "aps": {
                "alert": {
                    "title": "苹果离线展示的标题",
                    "body": "苹果离线展示的内容"
                },
                "content-available": 0,
                "sound": "default"
            },
            "auto_badge": "+1"
        }
    }
}

UniPushEntity实体类

根据自己业务逻辑去设计所需的实体–非必须

package org.springblade.ext.entity;

import lombok.Data;

@Data
public class UniPushEntity {

	//推送消息业务类型: 
    //1:待办  2:待阅 ---按传入的uids推送 3: 系统通知-- 推送所有人
	private String notifyType;
	//业务系统用户ids 用英文逗号隔开
    //☆☆☆数据库保存cid和uid之间的关系
	private String uids;  
	//推送标题
	private String title;
	//推送内容
	private String content;

}

url工具类PushConstant

此工具类用来统一管理API地址

package org.springblade.ext.utils;

public interface PushConstant {
	
	//应用基本信息可以在DCloud管理后台获取---https://dev.dcloud.net.cn/pages/common/login  登录后在推送配置处获取
  
	String APP_ID = "APP_ID";
	String APP_KEY = "APP_KEY";
	String MASTER_SECRET = "MASTER_SECRET";
	String BASE_URL = "https://restapi.getui.com/v2/" + APP_ID;

	//API 地址
	String AUTH_URL = BASE_URL + "/auth";  //获取token
	String CID_SINGLE = BASE_URL + "/push/single/cid"; //根据cid单推消息
	String ALIAS_SINGLE = BASE_URL + "/push/single/alias"; //根据别名单推消息
	String CID_TO_LIST = BASE_URL + "/push/list/cid"; //根据cid 批量推
	String TO_APP = BASE_URL + "/push/all"; //群推
	String CREATED_MESSAGE = BASE_URL +"/push/list/message"; //创建消息 为批推做准备
	String BIND_ALIAS = BASE_URL + "/user/alias"; // cid 绑定别名

}

PushRestApi推送实现类

此类是据业务逻辑集成所需的推送API: 1.群推 2.根据单个cid推送 3. 根据cid列表批量推(所有cid接收接收同一条消息)

统一请求集成

不管什么API都统一使用这个方法发送请求


	/**
	 *   统一发送请求
	 * 	 return 个推标准返回对象
	 */
	private static JSONObject sendPostRequest(String url,String requestBody){
		JSONObject result = new JSONObject();
		//获取token 已在方法体里做过期判断
		getToken();
		try{
			HttpResponse response = HttpUtil.createPost(url)
				.header("token",token)
				.body(requestBody)
				.execute();
			if(response.getStatus() == 200){
				result = JSON.parseObject(response.body());
				if(!result.getInteger("code").equals(0)){
					result.put("code",1);
				}
			}else{
				result.put("code",1);
			}
		}catch (Exception e){
			result.put("code",1);
			e.printStackTrace();
		}
		return result;
	}
鉴权–获取个推token
	
/**
	 *   获取个推服务的token
	 *   使用静态变量保存 token、有效时间 expired --此变量在工具类里面定义为静态变量
	 */
	synchronized public static void getToken(){
		if(System.currentTimeMillis() > expireTime){
			String appKey = PushConstant.APP_KEY;
			String timeStamp = String.valueOf(System.currentTimeMillis());
			String masterSecret  = PushConstant.MASTER_SECRET;
			String sign = getSHA256Str(appKey+timeStamp+masterSecret);
			if(StringUtils.isNotBlank(sign)){
				try{
					JSONObject requestBody = new JSONObject();
					requestBody.put("sign",sign);
					requestBody.put("timestamp",timeStamp);
					requestBody.put("appkey",appKey);
					String url = PushConstant.AUTH_URL;
					HttpResponse response = HttpUtil.createPost(url)
						.header("token",token)
						.body(requestBody.toJSONString())
						.execute();
					JSONObject result;
					if(response.getStatus() == 200){
						result = JSON.parseObject(response.body());
						if(result.getInteger("code").equals(0)){
							JSONObject data =  JSON.parseObject(result.get("data").toString());
							token = data.getString("token");
							expireTime = data.getLong("expire_time");
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}
			}
		}

	}


	/***
	 * 利用Apache的工具类实现SHA-256加密
	 * @param str 加密后的报文
	 * @return
	 */
	public static String getSHA256Str(String str){
		MessageDigest messageDigest;
		String encdeStr = "";
		try {
			messageDigest = MessageDigest.getInstance("SHA-256");
			byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
			encdeStr = Hex.encodeHexString(hash);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encdeStr;
	}
cid单推
	/**  push_message 为在线通道消息,push_channel为离线通道消息
	 * 单cid推送transmission
	 * @Param uniPushEntity
	 */
	public static Boolean cidToSingleTrans(UniPushEntity uniPushEntity,List<String> cidList){
		JSONObject requestBody = new JSONObject();
		JSONObject settings = new JSONObject();
		settings.put("ttl",7200000);
		JSONObject audience = new JSONObject();
		String title = uniPushEntity.getTitle();
		String content = uniPushEntity.getContent();
		audience.put("cid", cidList);
		JSONObject push_message = new JSONObject();
		JSONObject payload = new JSONObject();
		payload.put("notifyType",uniPushEntity.getNotifyType());
		payload.put("path","pages/home/page");
		payload.put("click_type","intent");
		JSONObject obj = new JSONObject();
		obj.put("title",title);
		obj.put("content",content);
		obj.put("payload",payload);
		String transmission = obj.toJSONString();
		push_message.put("transmission",transmission);
		requestBody.put("request_id", System.currentTimeMillis());
		requestBody.put("settings",settings);
		requestBody.put("audience",audience);
		requestBody.put("push_message",push_message);
		requestBody.put("push_channel",createPushChannel(title,content,payload));
		String url = PushConstant.CID_SINGLE;
		JSONObject result = sendPostRequest(url,requestBody.toJSONString());
		return result.getInteger("code").equals(0);
	}/**
	 *  创建离线通道消息内容
	 * @param title
	 * @param content
	 * @param payload
	 * @return JSONObject push_channel
	 */
	public static  JSONObject createPushChannel(String title,String content,JSONObject payload){
		//1 android
		JSONObject push_channel = new JSONObject();
		JSONObject android = new JSONObject();
		JSONObject ups = new JSONObject();
		JSONObject notification = new JSONObject();
		notification.put("title",title);
		notification.put("body",content);
		notification.put("click_type","intent");
		String intent = "intent://io.dcloud.unipush/?#Intent;scheme=unipush;launchFlags=0x4000000;" +
			"component=com.kluntech.pmiss/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=" + title  + ";S.content=" +content
			+ ";S.payload=" + payload.toJSONString() + ";end";
//		String intent = "intent://io.dcloud.unipush/?#Intent;scheme=unipush;launchFlags=0x4000000;component=com.kluntech.pmiss/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=intent测试标题;S.content=intent测试内容;S.payload=test;end";
		notification.put("intent",intent);
		ups.put("notification",notification);
		android.put("ups",ups);
		//2 ios
		JSONObject ios = new JSONObject();
		JSONObject aps = new JSONObject();
		JSONObject alert = new JSONObject();
		alert.put("title",title);
		alert.put("body",content);
		aps.put("alert",alert);
		aps.put("content-available",0);
		aps.put("sound","default");
		ios.put("aps",aps);
		ios.put("type","notify");
		ios.put("auto_badge","+1");
		ios.put("payload",payload.toJSONString());

		push_channel.put("android",android);
		push_channel.put("ios",ios);
		return push_channel;
	}
cid批量推
	/**
	 *  【toList】执行cid批量推
	 * @param uniPushEntity
	 */
	public static Boolean cidToList(UniPushEntity uniPushEntity,List<String> cidList){
		JSONObject requestBody = new JSONObject();
		JSONObject audience = new JSONObject();
		audience.put("cid",cidList);
		String taskId = createMessage(uniPushEntity);
		requestBody.put("audience",audience);
		requestBody.put("taskid",taskId);
		requestBody.put("is_async",false);
		String url = PushConstant.CID_TO_LIST;
		JSONObject result = sendPostRequest(url,requestBody.toJSONString());
		return result.getInteger("code").equals(0);
	}/**
	 * 创建消息 统一透传消息
	 * @param uniPushEntity
	 * @return taskId
	 */
	public static String createMessage(UniPushEntity uniPushEntity){
		JSONObject requestBody = new JSONObject();
		JSONObject settings = new JSONObject();
		String title = uniPushEntity.getTitle();
		String content = uniPushEntity.getContent();
		String notifyType = uniPushEntity.getNotifyType();
		//消息生存时间
		settings.put("ttl",7200000);
		//push_message
		JSONObject push_message = new JSONObject();
		JSONObject payload = new JSONObject();
		payload.put("notifyType",notifyType);
		payload.put("path","pages/home/page");
		payload.put("click_type","intent");
		JSONObject obj = new JSONObject();
		obj.put("title",title);
		obj.put("content",content);
		obj.put("payload",payload);
		String transmission = obj.toJSONString();
		push_message.put("transmission",transmission);
		requestBody.put("settings",settings);
		requestBody.put("push_message",push_message);


		//push_chanel 离线通道消息内容

		requestBody.put("push_channel",createPushChannel(title,content,payload));

		String url = PushConstant.CREATED_MESSAGE;
		JSONObject result = sendPostRequest(url,requestBody.toJSONString());
		String taskId = "";
		if(Func.isNotEmpty(result)){
			if(result.getInteger("code").equals(0)){
				JSONObject data =  JSON.parseObject(result.getString("data"));
				taskId = data.getString("taskid");
			}
		}
		return taskId;
	}
群推–推送给所有人
/**
	 * 【toAPP】群推
	 * @param uniPushEntity
	 */
	public static Boolean toApp(UniPushEntity uniPushEntity){
		JSONObject requestBody = new JSONObject();
		JSONObject settings = new JSONObject();
		settings.put("ttl",7200000);
		JSONObject push_message = new JSONObject();
		JSONObject payload = new JSONObject();
		String title = uniPushEntity.getTitle();
		String content = uniPushEntity.getContent();
		String notifyType = uniPushEntity.getNotifyType();
		payload.put("notifyType",notifyType);
		payload.put("path","pages/home/page");
		payload.put("click_type","intent");
		JSONObject obj = new JSONObject();
		obj.put("title",title);
		obj.put("content",content);
		obj.put("payload",payload);
		String transmission = obj.toJSONString();
		push_message.put("transmission",transmission);
		requestBody.put("push_channel",createPushChannel(title,content,payload));
		requestBody.put("settings",settings);
		requestBody.put("push_message",push_message);
		requestBody.put("audience","all");
		requestBody.put("request_id", System.currentTimeMillis());
		String url = PushConstant.TO_APP;
		JSONObject result = sendPostRequest(url,requestBody.toJSONString());
		return result.getInteger("code").equals(0);
	}
完整代码
package org.springblade.ext.utils;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.SpringUtil;
import org.springblade.ext.entity.AppPushBasicEntity;
import org.springblade.ext.entity.UniPushEntity;
import org.springblade.ext.service.IAppPushBasicService;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

public class PushRestApi {

	private static String token = "66b3933018447fc5b6c061b6f2542bd032702dc2d1d9359cf362d594fc10a74f"; //鉴权token
	private static Long expireTime = 1699086561945L;  //token 过期时间戳
	private static  IAppPushBasicService appPushBasicService;

	private static IAppPushBasicService getAppPushBasicService() {
		if (appPushBasicService == null) {
			appPushBasicService = SpringUtil.getBean(IAppPushBasicService.class);
		}
		return appPushBasicService;
	}

	/**
	 * 推送入口  我这里是数据库绑定了cid和userId  根据uid查找cid进行推送
	 * @param uniPushEntity
	 */
	public static  Boolean push(UniPushEntity uniPushEntity){
		String notifyType = uniPushEntity.getNotifyType();
		String uids = uniPushEntity.getUids();
		List<String> cidList = getCids(uids); 
		if(notifyType.equals("1") || notifyType.equals("2")){
			if(cidList.size() > 1 ){
				 return  cidToList(uniPushEntity,cidList);
			}else{
				return cidToSingleTrans(uniPushEntity,cidList);
			}
		}else{
			return toApp(uniPushEntity);
		}
	}




	/**
	 *  【toList】执行cid批量推
	 * @param uniPushEntity
	 */
	public static Boolean cidToList(UniPushEntity uniPushEntity,List<String> cidList){
		JSONObject requestBody = new JSONObject();
		JSONObject audience = new JSONObject();
		audience.put("cid",cidList);
		String taskId = createMessage(uniPushEntity);
		requestBody.put("audience",audience);
		requestBody.put("taskid",taskId);
		requestBody.put("is_async",false);
		String url = PushConstant.CID_TO_LIST;
		JSONObject result = sendPostRequest(url,requestBody.toJSONString());
		return result.getInteger("code").equals(0);
	}

	/**
	 * 【toAPP】群推
	 * @param uniPushEntity
	 */
	public static Boolean toApp(UniPushEntity uniPushEntity){
		JSONObject requestBody = new JSONObject();
		JSONObject settings = new JSONObject();
		settings.put("ttl",7200000);
		JSONObject push_message = new JSONObject();
		JSONObject payload = new JSONObject();
		String title = uniPushEntity.getTitle();
		String content = uniPushEntity.getContent();
		String notifyType = uniPushEntity.getNotifyType();
		payload.put("notifyType",notifyType);
		payload.put("path","pages/home/page");
		payload.put("click_type","intent");
		JSONObject obj = new JSONObject();
		obj.put("title",title);
		obj.put("content",content);
		obj.put("payload",payload);
		String transmission = obj.toJSONString();
		push_message.put("transmission",transmission);
		requestBody.put("push_channel",createPushChannel(title,content,payload));
		requestBody.put("settings",settings);
		requestBody.put("push_message",push_message);
		requestBody.put("audience","all");
		requestBody.put("request_id", System.currentTimeMillis());
		String url = PushConstant.TO_APP;
		JSONObject result = sendPostRequest(url,requestBody.toJSONString());
		return result.getInteger("code").equals(0);
	}


	/**
	 * 单cid推送transmission
	 * @Param uniPushEntity
	 */
	public static Boolean cidToSingleTrans(UniPushEntity uniPushEntity,List<String> cidList){
		JSONObject requestBody = new JSONObject();
		JSONObject settings = new JSONObject();
		settings.put("ttl",7200000);
		JSONObject audience = new JSONObject();
		String title = uniPushEntity.getTitle();
		String content = uniPushEntity.getContent();
		audience.put("cid", cidList);
		JSONObject push_message = new JSONObject();
		JSONObject payload = new JSONObject();
		payload.put("notifyType",uniPushEntity.getNotifyType());
		payload.put("path","pages/home/page");
		payload.put("click_type","intent");
		JSONObject obj = new JSONObject();
		obj.put("title",title);
		obj.put("content",content);
		obj.put("payload",payload);
		String transmission = obj.toJSONString();
		push_message.put("transmission",transmission);
		requestBody.put("request_id", System.currentTimeMillis());
		requestBody.put("settings",settings);
		requestBody.put("audience",audience);
		requestBody.put("push_message",push_message);
		requestBody.put("push_channel",createPushChannel(title,content,payload));
		String url = PushConstant.CID_SINGLE;
		JSONObject result = sendPostRequest(url,requestBody.toJSONString());
		return result.getInteger("code").equals(0);
	}

	/**
	 *创建离线通道消息内容
	 * @param title
	 * @param content
	 * @param payload
	 * @return JSONObject push_channel
	 */
	public static  JSONObject createPushChannel(String title,String content,JSONObject payload){
		//1 android
		JSONObject push_channel = new JSONObject();
		JSONObject android = new JSONObject();
		JSONObject ups = new JSONObject();
		JSONObject notification = new JSONObject();
		notification.put("title",title);
		notification.put("body",content);
		notification.put("click_type","intent");
		String intent = "intent://io.dcloud.unipush/?#Intent;scheme=unipush;launchFlags=0x4000000;" +
			"component=com.kluntech.pmiss/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=" + title  + ";S.content=" +content
			+ ";S.payload=" + payload.toJSONString() + ";end";
//		String intent = "intent://io.dcloud.unipush/?#Intent;scheme=unipush;launchFlags=0x4000000;component=com.kluntech.pmiss/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title=intent测试标题;S.content=intent测试内容;S.payload=test;end";
		notification.put("intent",intent);
		ups.put("notification",notification);
		android.put("ups",ups);
		//2 ios
		JSONObject ios = new JSONObject();
		JSONObject aps = new JSONObject();
		JSONObject alert = new JSONObject();
		alert.put("title",title);
		alert.put("body",content);
		aps.put("alert",alert);
		aps.put("content-available",0);
		aps.put("sound","default");
		ios.put("aps",aps);
		ios.put("type","notify");
		ios.put("auto_badge","+1");
		ios.put("payload",payload.toJSONString());

		push_channel.put("android",android);
		push_channel.put("ios",ios);
		return push_channel;
	}
	/**
	 * 创建消息 统一透传消息
	 * @param uniPushEntity
	 * @return taskId
	 */
	public static String createMessage(UniPushEntity uniPushEntity){
		JSONObject requestBody = new JSONObject();
		JSONObject settings = new JSONObject();
		String title = uniPushEntity.getTitle();
		String content = uniPushEntity.getContent();
		String notifyType = uniPushEntity.getNotifyType();
		//消息生存时间
		settings.put("ttl",7200000);
		//push_message
		JSONObject push_message = new JSONObject();
		JSONObject payload = new JSONObject();
		payload.put("notifyType",notifyType);
		payload.put("path","pages/home/page");
		payload.put("click_type","intent");
		JSONObject obj = new JSONObject();
		obj.put("title",title);
		obj.put("content",content);
		obj.put("payload",payload);
		String transmission = obj.toJSONString();
		push_message.put("transmission",transmission);
		requestBody.put("settings",settings);
		requestBody.put("push_message",push_message);


		//push_chanel 离线通道消息内容

		requestBody.put("push_channel",createPushChannel(title,content,payload));

		String url = PushConstant.CREATED_MESSAGE;
		JSONObject result = sendPostRequest(url,requestBody.toJSONString());
		String taskId = "";
		if(Func.isNotEmpty(result)){
			if(result.getInteger("code").equals(0)){
				JSONObject data =  JSON.parseObject(result.getString("data"));
				taskId = data.getString("taskid");
			}
		}
		return taskId;
	}

	/**
	 *   获取个推服务的token
	 *   使用静态变量保存 token、有效时间 expired
	 */
	synchronized public static void getToken(){
		if(System.currentTimeMillis() > expireTime){
			String appKey = PushConstant.APP_KEY;
			String timeStamp = String.valueOf(System.currentTimeMillis());
			String masterSecret  = PushConstant.MASTER_SECRET;
			String sign = getSHA256Str(appKey+timeStamp+masterSecret);
			if(StringUtils.isNotBlank(sign)){
				try{
					JSONObject requestBody = new JSONObject();
					requestBody.put("sign",sign);
					requestBody.put("timestamp",timeStamp);
					requestBody.put("appkey",appKey);
					String url = PushConstant.AUTH_URL;
					HttpResponse response = HttpUtil.createPost(url)
						.header("token",token)
						.body(requestBody.toJSONString())
						.execute();
					JSONObject result;
					if(response.getStatus() == 200){
						result = JSON.parseObject(response.body());
						if(result.getInteger("code").equals(0)){
							JSONObject data =  JSON.parseObject(result.get("data").toString());
							token = data.getString("token");
							expireTime = data.getLong("expire_time");
						}
					}
				}catch (Exception e){
					e.printStackTrace();
				}
			}
		}

	}
	/**
	 * 根据uids 获取推送的cids
	 * @param uids
	 * @return List<String> getCids
	 */
	public static List<String> getCids(String uids){
		List<Long> uidList = Func.toLongList(uids);
		QueryWrapper<AppPushBasicEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("user_id",uidList);
		queryWrapper.eq("is_expired",0);
		List<AppPushBasicEntity> list =  getAppPushBasicService().list(queryWrapper);
		List<String> resultList = list.stream().map(item -> item.getClientId()).collect(Collectors.toList());
		return resultList;
	}
	//统一发送请求
	private static JSONObject sendPostRequest(String url,String requestBody){
		JSONObject result = new JSONObject();
		//获取token 已在方法体里做过期判断
		getToken();
		try{
			HttpResponse response = HttpUtil.createPost(url)
				.header("token",token)
				.body(requestBody)
				.execute();
			if(response.getStatus() == 200){
				result = JSON.parseObject(response.body());
				if(!result.getInteger("code").equals(0)){
					result.put("code",1);
				}
			}else{
				result.put("code",1);
			}
		}catch (Exception e){
			result.put("code",1);
			e.printStackTrace();
		}
		return result;
	}
	/***
	 * 利用Apache的工具类实现SHA-256加密
	 * @param str 加密后的报文
	 * @return
	 */
	public static String getSHA256Str(String str){
		MessageDigest messageDigest;
		String encdeStr = "";
		try {
			messageDigest = MessageDigest.getInstance("SHA-256");
			byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
			encdeStr = Hex.encodeHexString(hash);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return encdeStr;
	}
}

文章来源:https://blog.csdn.net/Astonishing_/article/details/135284420
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。