个推-消息推送工具类

说明

个推集成比较方便,就是请求的第三方api
以下对其进行工具类的封装
我用的是dcloud第三方
https://dev.dcloud.net.cn/app/index
申请步骤,不在此说明

1.封装消息实体

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Objects;

/**
 * desc: 个推透传消息
 *
 * @author qts
 * @date 2022/4/1 0001
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Accessors(chain = true)
public class Transmission implements Serializable {

    private static final long serialVersionUID=1L;

    /**
     * 通知标题
     */
    private String title;
    /**
     * 通知内容
     */
    private String content;
    /**
     * 自定义数据
     */
    private String payload;

}

2. 工具类

使用了redis进行缓存token

package com.intellsite.common.redis.utils.getui;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.intellsite.common.redis.utils.RedisUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * desc: 个推消息推送工具
 *
 * @author qts
 * @date 2022/3/31 0031
 */
public class PushUtil {

    private PushUtil() {
    }

    // 公司的应用参数:自行在个推中申请查询
    private final static String AppID = "";
    private final static String AppKey = "";
    private final static String AppSecret = "";
    private final static String MasterSecret = "";

    private final static String BaseUrl = "https://restapi.getui.com/v2/"+AppID;
    // 获取token的url
    private final static String AuthUrl = BaseUrl+"/auth";
    // cid单推url
    private final static String PushSingleCid = BaseUrl+"/push/single/cid";
    // cid批量推创建消息url
    private final static String CreateListMsg = BaseUrl+"/push/list/message";
    // cid批量推url
    private final static String PushBatchCid = BaseUrl+"/push/list/cid";

    // token缓存key
    private final static String GT_TOKEN_CACHE_KEY = "getui_token";
    // 测试用token
    private final static String Token = "";


    /**
     * 生成签名
     * @param appkey
     * @param mastersecret
     * @param timeStamp
     * @return
     */
    private static String generateSign(String appkey,String mastersecret,Long timeStamp) {
        // 格式
        String s = appkey + timeStamp + mastersecret;
        // SHA256加密算法
        String encrypt = sha256Encrypt(s);
        return encrypt;
    }

    /**
     * 对字符串SHA-256加密
     *
     * @param strSrc
     *            要加密的字符串
     * @return
     */
    public static String sha256Encrypt(String strSrc) {
        MessageDigest md = null;
        String strDes = null;
        String encName="SHA-256";
        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance(encName);
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }

    public static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    /**
     * 获取个推token
     * @return
     */
    private static String getToken() {
        // 从redis中获取token
        Object token = RedisUtil.get(GT_TOKEN_CACHE_KEY);
        if (token != null) {
            return token.toString();
        } else {

            // 请求api得到token
            long timestamp = System.currentTimeMillis();
            String sign = generateSign(AppKey, MasterSecret, timestamp);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("sign", sign);
            params.put("timestamp", String.valueOf(timestamp));
            params.put("appkey", AppKey);
            String body = JSON.toJSONString(params);
            String result = HttpRequest.post(AuthUrl)
                .header(Header.CONTENT_TYPE,"application/json;charset=utf-8")
                .body(body)
                .timeout(20000)
                .execute().body();
            System.out.println("result: "+result);
            String data = JSONObject.parseObject(result).getJSONObject("data").getString("token");
            //有效时间半天
            RedisUtil.set(GT_TOKEN_CACHE_KEY, data, 60*60*12);
            return data;
        }

    }


    /**
     * 单cid推送
     * @param cid 客户端ID
     * @param transmission 参数
     */
    public static void singlePush(String cid,Transmission transmission) {
        // 封装请求参数
        Map<String, Object> params = new HashMap<String, Object>();

        params.put("request_id", UUID.fastUUID().toString().replace("-",""));
        Map<String, Object> audience = new HashMap<String, Object>();
        // 接收人
        audience.put("cid", Arrays.asList(cid));//clientID
        params.put("audience", audience);
        // 消息内容
        Map<String, Object> push_message = new HashMap<String, Object>();

        // 透传
        //{title:"标题",content:"内容",payload:"自定义数据"}
        push_message.put("transmission",JSON.toJSONString(transmission));

        params.put("push_message", push_message);

        String body = JSON.toJSONString(params);
        // 获取token
        //String token = Token;
        String token = getToken();
        // cid单推
        String result = HttpRequest.post(PushSingleCid)
            .header("token",token)
            .body(body)
            .timeout(20000)
            .execute().body();
        System.out.println("result: "+result);

    }

    /**
     * cid批量推送
     * @param cids 客户端ID数组
     * @param transmission 参数
     */
    public static void batchPush(List<String> cids,Transmission transmission) {

        // 1.创建消息
        String taskiId = createMsg(transmission);

        // 2.批量cid推送
        cidPush(cids, taskiId);

    }

    /**
     * cid批量推
     * @param cids
     * @param taskiId
     */
    private static void cidPush(List<String> cids, String taskiId) {
        // 封装请求参数
        Map<String, Object> params = new HashMap<String, Object>();
        Map<String, Object> audience = new HashMap<String, Object>();
        // 接收人
        audience.put("cid", cids);//clientID
        params.put("audience", audience);
        params.put("taskid", taskiId);
        // 是否异步推送,true是异步,false同步。异步推送不会返回data详情
        params.put("is_async", true);

        String body = JSON.toJSONString(params);
        // 获取token
        //String token = Token;
        String token = getToken();
        // cid单推
        String result = HttpRequest.post(PushBatchCid)
            .header("token",token)
            .body(body)
            .timeout(20000)
            .execute().body();
        System.out.println("result: "+result);
    }

    /**
     * 创建消息
     * 用于批量推送
     * @param transmission
     * @return taskid 消息ID
     */
    private static String createMsg(Transmission transmission) {
        // 封装请求参数
        Map<String, Object> params = new HashMap<String, Object>();

        params.put("request_id", UUID.fastUUID().toString().replace("-",""));
        // 消息内容
        Map<String, Object> push_message = new HashMap<String, Object>();
        // 透传
        //{title:"标题",content:"内容",payload:"自定义数据"}
        push_message.put("transmission",JSON.toJSONString(transmission));
        params.put("push_message", push_message);

        String body = JSON.toJSONString(params);
        // 获取token
        //String token = Token;
        String token = getToken();
        // cid单推
        String result = HttpRequest.post(CreateListMsg)
            .header("token",token)
            .body(body)
            .timeout(20000)
            .execute().body();
        System.out.println("result: "+result);

        return JSONObject.parseObject(result).getJSONObject("data").getString("taskid");
    }

    public static void main(String[] args) {
        // 请求api得到token
        //token();

        // 消息体
        Transmission transmission = new Transmission();
        transmission.setTitle("title22");
        transmission.setContent("请及时审核22");
        transmission.setPayload("自定义数据22");

        String[] cids ={"188e37e4c3df943b46186c6f93357d44","22ddc1e5705531ce8283267091d66634"};
        // cid单推
        //singlePush("22ddc1e5705531ce8283267091d66634",transmission);

        // cid批量推
        batchPush(Arrays.asList(cids),transmission);
    }

    private static void token() {
        long timestamp = System.currentTimeMillis();
        String sign = generateSign(AppKey, MasterSecret, timestamp);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", sign);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("appkey", AppKey);
        String body = JSON.toJSONString(params);
        String result = HttpRequest.post(AuthUrl)
            .body(body)
            .timeout(20000)
            .execute().body();
        System.out.println("result: "+result);
        String data = JSONObject.parseObject(result).getJSONObject("data").getString("token");
        System.out.println(data);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值