赞
踩
官网地址:https://docs.getui.com/getui/
程序员不坑程序员,你copy后。直接能用,亲测~
如果帮到你。点个赞再走~
简介
注:新版和老版区别在于,新版不需要引入依赖,都通过Http请求
个推提供3种推送模式:
toSingle :简称“单推”,指向单个用户推送消息
toList:简称“批量推”,指向制定的一批用户推送消息
toApp:简称“群推”,指向APP符合筛选条件的所有用户推送消息,支持定速推送、定时推送,支持条件的交并补功能
废话不多说,上代码。
第一步
创建应用,并查看应用的基本信息。如图。
第二步
增加SHA256加密工具包。
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import java.security.MessageDigest;
public class SHAEncode {
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'};
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
public static String encodeSHA1(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String encodeSHA256(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
第三步
增加个推API。这个API类,你直接放到工程里就可以了。注释绝对明明白白。如果不行,联系我!!!
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* @author :Mall
* @date :Created in 2021-01-22
* @description :个推推送API
*/
@Component
public class IGtPushRestApi {
@Value("${igt.push.appId}")
private String appId;
@Value("${igt.push.appKey}")
private String appKey;
@Value("${igt.push.masterSecret}")
private String masterSecret;
private String baseUrl;
@Value("${igt.push.appId}")
public void setBaseUrl(String appId) {
this.baseUrl = "https://restapi.getui.com/v2/" + appId;
}
//存储个推的Token
@Resource(name = "redisTemplate1")
private RedisTemplate<String, Object> redisTemplate1;
//请求推送
@Resource
private RestTemplate restTemplate;
/**
* 单推,给指定用户推送
*
* @param cid 个推生成的用户唯一标识
* @param title 标题
* @param content 内容
* @param url 可为空没动作(其他值是自定义参数)
*/
public void pushToUser(String cid, String title, String content, String url) {
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append(" \"request_id\":\"" + System.currentTimeMillis() + "\","); //请求唯一标识号,10-32位之间
//推送条件
sb.append(" \"settings\":{");
sb.append(" \"ttl\":3600000");//消息离线时间设置,单位毫秒
sb.append(" },");
//推送用户
sb.append(" \"audience\":{");
sb.append(" \"cid\":[");
sb.append(" \"" + cid + "\""); //推送目标用户
sb.append(" ]");
sb.append(" },");
//个推参数
sb.append(" \"push_message\":{");
sb.append(" \"notification\":{");
sb.append(" \"title\":\"" + title + "\","); //通知消息标题,长度 ≤ 50
sb.append(" \"body\":\"" + content + "\","); //通知消息内容,长度 ≤ 256
if (StringUtils.isEmpty(url)) {
sb.append(" \"click_type\":\"none\""); //无动作
} else if (url.startsWith("http://") || url.startsWith("https://")) {//打开网页地址
sb.append(" \"click_type\":\"url\",\n");
sb.append(" \"url\":\"" + url + "\"\n");
} else if (url.startsWith("intent:")) { //打开App指定页面
sb.append(" \"click_type\":\"intent\",\n");
sb.append(" \"intent\":\"" + url + "\"\n");
} else { //自定义消息
sb.append(" \"click_type\":\"payload\",\n");
sb.append(" \"payload\":\"" + url + "\"\n");
}
sb.append(" }");
sb.append(" },");
//各厂商渠道配置,android 和 ios
sb.append(" \"push_channel\":{");
//ios
sb.append(" \"ios\":{");
sb.append(" \"type\":\"notify\",");
if (StringUtils.isNotEmpty(url)) {
sb.append(" \"payload\":\"" + url + "\",");
}
sb.append(" \"aps\":{");
sb.append(" \"alert\":{");
sb.append(" \"title\":\"" + title + "\",");
sb.append(" \"body\":\"" + content + "\"");
sb.append(" },");
sb.append(" \"content-available\":0,");
sb.append(" \"category\":\"ACTIONABLE\"");
sb.append(" },");
sb.append(" \"auto_badge\":\"+1\""); //icon上显示的数字 + 1
sb.append(" }");
sb.append(" },");
//android
sb.append(" \"android\":{");
sb.append(" \"ups\":{");
sb.append(" \"notification\":{");
sb.append(" \"title\":\"" + title + "\",");
sb.append(" \"body\":\"" + content + "\",");
if (StringUtils.isEmpty(url)) {
sb.append(" \"click_type\":\"none\""); //无动作
} else if (url.startsWith("http://") || url.startsWith("https://")) {//打开网页地址
sb.append(" \"click_type\":\"url\",\n");
sb.append(" \"url\":\"" + url + "\"\n");
} else if (url.startsWith("intent:")) { //打开App指定页面
sb.append(" \"click_type\":\"intent\",\n");
sb.append(" \"intent\":\"" + url + "\"\n");
} else { //自定义消息
sb.append(" \"click_type\":\"payload\",\n");
sb.append(" \"payload\":\"" + url + "\"\n");
}
sb.append(" }");
sb.append(" }");
sb.append(" }");
sb.append("}");
//推送
sendRqeust("/push/single/cid", sb.toString());
}
/**
* 批量推,给指定多个Cid用户
*
* @param cidList 用户列表
* @param title 标题
* @param content 内容
* @param url 可为空没动作(其他值是自定义参数)
*/
public void pushToBatch(List<String> cidList, String title, String content, String url) {
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append(" \"audience\": {");
sb.append(" \"cid\": [");
for (int i = 0; i < cidList.size(); i++) {
sb.append(cidList.get(i) + (i == cidList.size() - 1 ? "" : ","));
}
sb.append(" ]");
sb.append(" },");
sb.append(" \"taskid\": \"" + createMessage(title, content, url) + "\",");
sb.append(" \"is_async\": true");
sb.append("}");
//发送
sendRqeust("/push/list/cid", sb.toString());
}
/**
* 群推,给APP所有人
*
* @param title 标题
* @param content 内容
* @param url 可为空没动作(其他值是自定义参数)
*/
public void pushToApp(String title, String content, String url) {
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append(" \"request_id\":\"" + System.currentTimeMillis() + "\",");
sb.append(" \"group_name\":\"sendGroup\",");
sb.append(" \"settings\":{");
sb.append(" \"ttl\":3600000");
sb.append(" },");
sb.append(" \"audience\":\"all\",");
sb.append(" \"push_message\":{");
sb.append(" \"notification\":{");
sb.append(" \"title\":\"" + title + "\",");
sb.append(" \"body\":\"" + content + "\",");
if (StringUtils.isEmpty(url)) {
sb.append(" \"click_type\":\"none\""); //无动作
} else if (url.startsWith("http://") || url.startsWith("https://")) {//打开网页地址
sb.append(" \"click_type\":\"url\",\n");
sb.append(" \"url\":\"" + url + "\"\n");
} else if (url.startsWith("intent:")) { //打开App指定页面
sb.append(" \"click_type\":\"intent\",\n");
sb.append(" \"intent\":\"" + url + "\"\n");
} else { //自定义消息
sb.append(" \"click_type\":\"payload\",\n");
sb.append(" \"payload\":\"" + url + "\"\n");
}
sb.append(" }");
sb.append(" },");
//各厂商渠道配置,android 和 ios
sb.append(" \"push_channel\":{");
//ios
sb.append(" \"ios\":{");
sb.append(" \"type\":\"notify\",");
if (StringUtils.isNotEmpty(url)) {
sb.append(" \"payload\":\"" + url + "\",");
}
sb.append(" \"aps\":{");
sb.append(" \"alert\":{");
sb.append(" \"title\":\"" + title + "\",");
sb.append(" \"body\":\"" + content + "\"");
sb.append(" },");
sb.append(" \"content-available\":0,");
sb.append(" \"category\":\"ACTIONABLE\"");
sb.append(" },");
sb.append(" \"auto_badge\":\"+1\""); //icon上显示的数字 + 1
sb.append(" }");
sb.append(" },");
//android
sb.append(" \"android\":{");
sb.append(" \"ups\":{");
sb.append(" \"notification\":{");
sb.append(" \"title\":\"" + title + "\",");
sb.append(" \"body\":\"" + content + "\",");
if (StringUtils.isEmpty(url)) {
sb.append(" \"click_type\":\"none\""); //无动作
} else if (url.startsWith("http://") || url.startsWith("https://")) {//打开网页地址
sb.append(" \"click_type\":\"url\",\n");
sb.append(" \"url\":\"" + url + "\"\n");
} else if (url.startsWith("intent:")) { //打开App指定页面
sb.append(" \"click_type\":\"intent\",\n");
sb.append(" \"intent\":\"" + url + "\"\n");
} else { //自定义消息
sb.append(" \"click_type\":\"payload\",\n");
sb.append(" \"payload\":\"" + url + "\"\n");
}
sb.append(" }");
sb.append(" }");
sb.append(" }");
sb.append("}");
//推送
sendRqeust("/push/all", sb.toString());
}
/**
* 获取个推Token
*
* @return
*/
private String findToken() {
String token = "";
if (redisTemplate1.hasKey("igttoken")) { //redis存在token
token = String.valueOf(redisTemplate1.opsForValue().get("igttoken"));
} else {
long timestamp = System.currentTimeMillis();
String sign = SHAEncode.encodeSHA256(appKey + timestamp + masterSecret);
String bodyData = new String("{\"sign\": \"" + sign + "\",\"timestamp\": \"" + timestamp + "\", \"appkey\": \"" + appKey + "\"}");
JSONObject jo = JSONObject.parseObject(sendRqeust("/auth", bodyData));
JSONObject datajo = jo.getJSONObject("data");
token = datajo.getString("token");
//Redis存储Token
redisTemplate1.opsForValue().set("igttoken", token, datajo.getLong("expire_time"), TimeUnit.MILLISECONDS);
}
return token;
}
/**
* 发送个推请求
*
* @param path 发送路径
* @param dataJson 发送Json数据
* @return
*/
private String sendRqeust(String path, String dataJson) {
//设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/json;charset=UTF-8"));
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
if (!path.startsWith("/auth")) { //如果是获取token,则不拼接
headers.add("token", findToken());
}
//拼接JSON串
HttpEntity<String> httpEntity = new HttpEntity<String>(dataJson, headers);
String result = restTemplate.postForObject(baseUrl + "" + path, httpEntity, String.class);
return result;
}
/**
* 创建消息
*
* @param title 标题
* @param content 内容
* @param url 可为空没动作(其他值是自定义参数)
* @return taskid 批量推送需要用到的参数
*/
private String createMessage(String title, String content, String url) {
StringBuffer sb = new StringBuffer();
sb.append("{");
sb.append(" \"request_id\":\"" + System.currentTimeMillis() + "\",");
sb.append(" \"group_name\":\"批量推送消息\",");
sb.append(" \"settings\":{");
sb.append(" \"ttl\":3600000");
sb.append(" },");
sb.append(" \"push_message\":{");
sb.append(" \"notification\":{ ");
sb.append(" \"title\":\"" + title + "\",");
sb.append(" \"body\":\"" + content + "\",");
if (StringUtils.isEmpty(url)) {
sb.append(" \"click_type\":\"none\""); //无动作
} else if (url.startsWith("http://") || url.startsWith("https://")) {//打开网页地址
sb.append(" \"click_type\":\"url\",");
sb.append(" \"url\":\"" + url + "\"");
} else if (url.startsWith("intent:")) { //打开App指定页面
sb.append(" \"click_type\":\"intent\",");
sb.append(" \"intent\":\"" + url + "\"");
} else { //自定义消息
sb.append(" \"click_type\":\"payload\",");
sb.append(" \"payload\":\"" + url + "\"");
}
sb.append(" }");
sb.append(" },");
//各厂商渠道配置,android 和 ios
sb.append(" \"push_channel\":{");
//ios
sb.append(" \"ios\":{");
sb.append(" \"type\":\"notify\",");
if (StringUtils.isNotEmpty(url)) {
sb.append(" \"payload\":\"" + url + "\",");
}
sb.append(" \"aps\":{");
sb.append(" \"alert\":{");
sb.append(" \"title\":\"" + title + "\",");
sb.append(" \"body\":\"" + content + "\"");
sb.append(" },");
sb.append(" \"content-available\":0,");
sb.append(" \"category\":\"ACTIONABLE\"");
sb.append(" },");
sb.append(" \"auto_badge\":\"+1\""); //icon上显示的数字 + 1
sb.append(" }");
sb.append(" },");
//android
sb.append(" \"android\":{");
sb.append(" \"ups\":{");
sb.append(" \"notification\":{");
sb.append(" \"title\":\"" + title + "\",");
sb.append(" \"body\":\"" + content + "\",");
if (StringUtils.isEmpty(url)) {
sb.append(" \"click_type\":\"none\""); //无动作
} else if (url.startsWith("http://") || url.startsWith("https://")) {//打开网页地址
sb.append(" \"click_type\":\"url\",\n");
sb.append(" \"url\":\"" + url + "\"\n");
} else if (url.startsWith("intent:")) { //打开App指定页面
sb.append(" \"click_type\":\"intent\",\n");
sb.append(" \"intent\":\"" + url + "\"\n");
} else { //自定义消息
sb.append(" \"click_type\":\"payload\",\n");
sb.append(" \"payload\":\"" + url + "\"\n");
}
sb.append(" }");
sb.append(" }");
sb.append(" }");
sb.append("}");
String result = sendRqeust("/push/list/message", sb.toString());
JSONObject jsonObject = JSONObject.parseObject(result);
JSONObject dataJo = jsonObject.getJSONObject("data");
return dataJo.getString("taskid");
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。