发送通知
/**
* 发送通知
* @param title
* @param content
* @param type
* @param contentId
* @return
*/
public boolean uniPush(String title,String content,Integer type,Integer contentId){
Map map=new HashMap();
map.put("type",type);
map.put("contentId",contentId);
map.put("title",title);
map.put("content",content);
JSONObject jsonObj=new JSONObject(map);
String s = jsonObj.toString();
s= StringUtils.replace(s,"\"","\\\"");
String uuid = UUID.randomUUID().toString();
String token1 = getToken(false);
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
String contentJson ="{\n" +
" \"request_id\":\""+uuid+"\",\n" +
" \"settings\":{\n" +
" \"ttl\":3600000,\n" +
" \"strategy\":{\n" +
" \"default\":1,\n" +
" \"ios\":4\n" +
//" \"hw\":2,\n" +
//" \"xm\":2,\n" +
//" \"vv\":2\n" +
" }\n" +
" },\n" +
//" \"audience\":{\n" +
//" \"cid\":[\n" +
//" \"7da0f6cdde22a1f2a995a5ec4f21ed21\"\n" +
//" ]\n" +
//" },\n" +
" \"audience\":\"all\",\n" +
" \"push_message\":{\n" +
" \"transmission\":\""+s+"\"\n" +
" },\n" +
" \"push_channel\":{\n" +
" \"android\":{\n" +
" \"ups\":{\n" +
" \"notification\":{\n" +
" \"title\":\""+title+"\",\n" +
" \"body\":\""+content+"\",\n" +
" \"click_type\":\"intent\",\n" +
" \"intent\":\"intent:#Intent;action=android.intent.action.oppopush;launchFlags=0x14000000;component=uni.UNI91FE773/io.dcloud.PandoraEntry;S.UP-OL-SU=true;S.title="+title+";S.content="+content+";S.payload="+s+";end\"\n" +
" }\n" +
" }\n" +
" },\n" +
" \"ios\":{\n" +
" \"type\":\"notify\",\n" +
" \"payload\":\""+s+"\",\n" +
" \"aps\":{\n" +
" \"alert\":{\n" +
" \"title\":\""+title+"\",\n" +
" \"body\":\""+content+"\"\n" +
" },\n" +
" \"content-available\":0\n" +
//" \"sound\":\"default\"\n" +//铃声
" }\n" +
//" \"auto_badge\":\"+1\"\n" +//角标
" }\n" +
" }\n" +
" }";
//System.out.println(contentJson);
RequestBody body = RequestBody.create(mediaType,contentJson);
Request request = new Request.Builder()
//.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/push/single/cid")//根据cid单推
.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/push/all")
.method("POST", body)
.addHeader("Content-Type", "application/json;charset=utf-8")
.addHeader("token", token1)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String string = response.body().string();
Map json = (Map) JSONObject.parse(string);
Integer code = (Integer)json.get("code");
if( code == 10001){
//token失效
token1 = getToken(true);//重新强制获得token
//重试一次
request = new Request.Builder()
//.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/push/single/cid")根据cid单推
.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/push/all")
.method("POST", body)
.addHeader("Content-Type", "application/json;charset=utf-8")
.addHeader("token", token1)
.build();
response = client.newCall(request).execute();
string = response.body().string();
json = (Map) JSONObject.parse(string);
code = (Integer)json.get("code");
if( code == 10001){
//token失效
return false;
}
}
String msg = (String)json.get("msg");
if(StringUtils.equals(msg,"success")){
return true;
}else {
log.info(msg);
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
/**
* 缓存个推token的方法
*/
public String getToken(boolean retrieve){
if(retrieve){
//强制重新获取 auth
String auth = auth();
if(StringUtils.isBlank(auth)){
log.info("个推鉴权获取token失败");
throw new YshopException("个推鉴权获取token失败");
}
long expireTime = 22L;//个腿 auth 24小时失效,这里设置22小时,key自动删除后,会自动重新获取
redisTemplate.opsForValue().set(uniPushV2TokenRedisKey, auth , expireTime, TimeUnit.HOURS);
return auth;
}else {
//return "565656";
//优先使用redis中缓存的额auth
if(redisTemplate.hasKey(uniPushV2TokenRedisKey)){
return redisTemplate.opsForValue().get(uniPushV2TokenRedisKey);
}else{
String auth = auth();
if(StringUtils.isBlank(auth)){
log.info("个推鉴权获取token失败");
throw new YshopException("个推鉴权获取token失败");
}
long expireTime = 22L;//个腿 auth 24小时失效,这里设置22小时,key自动删除后,会自动重新获取
redisTemplate.opsForValue().set(uniPushV2TokenRedisKey, auth , expireTime, TimeUnit.HOURS);
return auth;
}
}
}
/**
* 获取鉴权token
* @return
*/
public String auth(){
long time = new Date().getTime();
String sign = DigestUtils.sha256Hex(appKey + time + masterSecret);
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
RequestBody body = RequestBody.create(mediaType, "{\"sign\": \""+sign+"\",\"timestamp\": \""+time+"\",\"appkey\": \"uRQw39Qjft6OWGu7d3L8H5\"}");
Request request = new Request.Builder()
.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/auth")
.method("POST", body)
.addHeader("Content-Type", "application/json;charset=utf-8")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String string = response.body().string();
Map json = (Map) JSONObject.parse(string);
Map data = (Map)json.get("data");
if(data == null){
return null;
}
String token=(String)data.get("token");
return token;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
app端处理透传通知和点击通知
在app.vue -> onLaunch方法中
//#ifdef APP-PLUS
plus.push.addEventListener("click", function(msg) {
//console.log("click:"+JSON.stringify(msg));
//console.log(msg.payload);
//console.log("clickmsg:"+JSON.stringify(msg));
//console.log(msg);
var payload={};
var platform = uni.getSystemInfoSync().platform;
if(platform == "ios"){
if(msg['type'] == "click"){
//通过苹果服务器通知过来的消息
payload=msg['payload'];
}else{
//通过个推透传,创建本地通知的消息
payload=JSON.parse(msg.payload);
}
}else if (platform == 'android'){
payload=msg.payload;
}
//console.log(payload.type);
if(payload.type==0){
setTimeout(function() {
uni.navigateTo({
url:"/pages/shop/GoodsCon/index?id="+payload.contentId,
})
}, 1000)
}else{
setTimeout(function() {
uni.navigateTo({
url:"/pages/shop/news/NewsDetail/index?id="+payload.contentId,
})
}, 1000)
}
//获得个推用户信息
//let pinf = plus.push.getClientInfo();
//console.log("pinf:"+JSON.stringify(pinf));
}, false);
plus.push.addEventListener("receive", function(msg) {
//console.log("receive:"+JSON.stringify(msg));
//console.log(msg.payload);
//获得个推用户信息
//let pinf = plus.push.getClientInfo();
//console.log("pinf:"+JSON.stringify(pinf));
var platform = uni.getSystemInfoSync().platform;
if(platform == "ios"){
//ios平台应用在前台时,不能收到通知消息,只能走透传,在创建一条本地消息
//if (msg.type == "receive"){// 这里判断触发的来源,否则一直推送。
var content = JSON.parse(msg.content);
plus.push.createMessage(content.content, JSON.stringify(msg.payload), { title: content.title });
//}
}else if (platform == 'android'){
plus.push.createMessage(msg.content, JSON.stringify(msg.payload), { title: msg.title });
}
}, false);
plus.push.getClientInfoAsync((info) => {
let cid = info["clientid"];
console.log("cid:"+cid);
uni.setStorageSync('cid',cid);
});
// #endif
这样app在线时透传,离线时厂商推送安卓,ios都可以了
在登录成功后,设置cid与用户id的关系,并且根居数据库上次用户设置的是否接受通知重新设置设备是否接受通知,在用户退出登录时,解除cid与用户id的关系,并做好app端的单点登录,否则用户登录多台设备,会之后最后一个设备收到通知
/**
* 添加黑名单用户
* @return
*/
public boolean black(String cid){
String token1 = uniPushUtilV2.getToken(false);
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/user/black/cid/"+cid)
.method("POST", body)
.addHeader("Content-Type", "application/json;charset=utf-8")
.addHeader("token", token1)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String string = response.body().string();
Map json = (Map) JSONObject.parse(string);
Integer code = (Integer)json.get("code");
if( code == 10001){
//token失效
token1 = uniPushUtilV2.getToken(true);//重新强制获得token
//重试一次
request = new Request.Builder()
.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/user/black/cid/"+cid)
.method("POST", body)
.addHeader("Content-Type", "application/json;charset=utf-8")
.addHeader("token", token1)
.build();
response = client.newCall(request).execute();
string = response.body().string();
json = (Map) JSONObject.parse(string);
code = (Integer)json.get("code");
if( code == 10001){
//token失效
return false;
}
}
String msg = (String)json.get("msg");
if(StringUtils.equals(msg,"success")){
return true;
}else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 移除黑名单用户
* @param cid
* @return
*/
public boolean shiftOutBlack(String cid){
String token1 = uniPushUtilV2.getToken(false);
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
RequestBody body = RequestBody.create(mediaType, "");
Request request = new Request.Builder()
.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/user/black/cid/"+cid)
.method("DELETE", body)
.addHeader("Content-Type", "application/json;charset=utf-8")
.addHeader("token", token1)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String string = response.body().string();
Map json = (Map) JSONObject.parse(string);
Integer code = (Integer)json.get("code");
if( code == 10001){
//token失效
token1 = uniPushUtilV2.getToken(true);//重新强制获得token
//重试一次
request = new Request.Builder()
.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/user/black/cid/"+cid)
.method("DELETE", body)
.addHeader("Content-Type", "application/json;charset=utf-8")
.addHeader("token", token1)
.build();
response = client.newCall(request).execute();
string = response.body().string();
json = (Map) JSONObject.parse(string);
code = (Integer)json.get("code");
if( code == 10001){
//token失效
return false;
}
}
String msg = (String)json.get("msg");
if(StringUtils.equals(msg,"success")){
return true;
}else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 查询用户是否在黑名单
* @param cid
* @return 返回true 表示在黑名单中
*/
public boolean userStatus(String cid){
String token1 = uniPushUtilV2.getToken(false);
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/user/status/"+cid)
.method("GET", null)
.addHeader("token", token1)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String string = response.body().string();
Map json = (Map) JSONObject.parse(string);
Integer code = (Integer)json.get("code");
if( code == 10001){
//token失效
token1 = uniPushUtilV2.getToken(true);//重新强制获得token
//重试一次
request = new Request.Builder()
.url("https://restapi.getui.com/v2/gm8KC6iRJp6Tp1TyxeWEI5/user/status/"+cid)
.method("GET", null)
.addHeader("Content-Type", "application/json;charset=utf-8")
.addHeader("token", token1)
.build();
response = client.newCall(request).execute();
string = response.body().string();
json = (Map) JSONObject.parse(string);
code = (Integer)json.get("code");
if( code == 10001){
//token失效
return false;
}
}
String msg = (String)json.get("msg");
if(StringUtils.equals(msg,"target user is invalid")){
return true;
}else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}