uniAPP uniPush(个推)

手机APP/开发
710
0
0
2022-03-29
标签   uni-app

首先开通UniPush推送服务

uniAPP uniPush(个推)

点击 配置 打开 推送配置页面

uniAPP uniPush(个推)

使用uniapp 云打包(在Hbuilder模块配置中勾选push模块后打包)

将 android包名 填写到上图中

uniAPP uniPush(个推)

获取 Android 应用签名

打开cmd 进入证书文件所在的文件夹

执行下方命令: keytool -list -v -keystore {your_app}.keystore

uniAPP uniPush(个推)

将上图标记内容 填写到图二的应用签名中

Ios bundle id 内填写iOS对应包名

开通 Uni Push,可以看到如下页面


uniAPP uniPush(个推)

这时云打包应该已经完成了

复制下载地址用手机浏览器打开 下载 安装登陆后.

点击上图预览可以看到


uniAPP uniPush(个推)

预计人数大于1 说明配置成功

点击确定发送消息


uniAPP uniPush(个推)


还可以通过后台服务推送消息代码如下:

Java代码

pom文件所需:

<!--个推推送-->
<dependency>
<groupId>com.gexin.platform</groupId>
<artifactId>gexin-rp-sdk-http</artifactId>
<version>4.1.0.5</version>
</dependency>
<!-- 个推依赖下载地址-->
<repositories>
<repository>
<id>getui-nexus</id>
<url>http://mvn.gt.igexin.com/nexus/content/repositories/releases/</url>
</repository>
</repositories>

推送工具类:

package com.patrol.app.utils;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.gexin.rp.sdk.base.IAliasResult;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.AbstractTemplate;
import com.gexin.rp.sdk.template.TransmissionTemplate;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @Description: 推送工具类(个推)
* @author:chaoyapeng
* @time:2020/11/24 11:22
* @Version V1.0
*/
@Slf4j
public class GeTuiPush {
    private static String url = "http://sdk.open.api.igexin.com/apiex.htm";
    private static String appId = "3ySHYDu1Sz9KoEtB9XIsi1";
    private static String appKey = "gdA5F8Uplm5gNO6CvwKta8";
    private static String masterSecret = "m5fFwJ2uJV8TAzjy6mbiA9";
    private static IGtPush igtPush = new IGtPush(url, appKey, masterSecret);
    /**
    * 为用户绑定别名
    * @param clientId 客户端身份id
    * @param alias 别名
    * @return
    */ 
    public static Boolean bindAlias(String clientId, String alias) {
    IAliasResult ret = null;
    try {
        ret = igtPush.bindAlias(appId, alias, clientId);
        log.info("is bindAlias res: {}", ret.getResponse());
    } catch (RequestException e) {
        e.printStackTrace();
    }
    if (ret != null) {
        Map res = ret.getResponse();
        if ("ok".equals(res.get("result").toString())) {
            return true;
        }
    }
    return false;
}

/**
* 解绑别名(单个clientid和别名解绑)
* @param clientId 客户端身份id
* @param alias 用户别名
* @return
*/
public static Boolean unBindAlias(String clientId, String alias) {
    IAliasResult ret = null;
    try {
        ret = igtPush.unBindAlias(appId, alias, clientId);
        log.info("is bindAlias res: {}", ret.getResponse());
    } catch (RequestException e) {
        e.printStackTrace();
    }
    if (ret != null) {
        Map res = ret.getResponse();
        if ("ok".equals(res.get("result").toString())) {
            return true;
        }
    }
    return false;
}

/**
* 全量解绑别名(绑定别名的所有clientid解绑)
* @param alias 用户别名
* @return
*/
public static Boolean unBindAliasAll(String alias) {
    IAliasResult ret = null;
    try {
        ret = igtPush.unBindAliasAll(appId, alias);
        log.info("is bindAlias res: {}", ret.getResponse());
    } catch (RequestException e) {
        e.printStackTrace();
    }
    if (ret != null) {
        Map res = ret.getResponse();
        if ("ok".equals(res.get("result").toString())) {
            return true;
        }
    }
    return false;
}

/**
* 单推(单个clientId/别名)
* @param pushContent 推送内容(JSON{title:'标题',content:'内容',payload:'携带参数'})
* @param type 类型【1.设备id(clientId) 2.别名】
* @param val 类型值(clientId/别名)
* @return
*/
public static Map pushMessageToSingle(String pushContent, int type, String val) {
    /*透传消息模版*/ 
    AbstractTemplate template = getTransmissionTemplate(pushContent);
    // 单推消息 
    SingleMessage message = new SingleMessage();
    message.setData(template);
    // 设置消息离线,并设置离线时间
    message.setOffline(true);
    // 离线有效时间,单位为毫秒,可选
    message.setOfflineExpireTime(72 * 3600 * 1000);
    message.setPriority(1);
    // 判断客户端是否wifi环境下推送。1为仅在wifi环境下推送,0为不限制网络环境,默认不限
    message.setPushNetWorkType(0);
    Target target = new Target();
    target.setAppId(appId);
    if (type == 1) {
        target.setClientId(val);
    } else {
        // 别名需要提前绑定
        target.setAlias(val);
    }
    IPushResult ret = null;
    try {
        ret = igtPush.pushMessageToSingle(message, target);
        log.info("is pushMessageToSingle res: {}", ret.getResponse());
    } catch (RequestException e) {
        e.printStackTrace();
        ret = igtPush.pushMessageToSingle(message, target, e.getRequestId());
    }
    if (ret != null) {
        return ret.getResponse();
    } else {
        log.error("个推单条推送服务器响应异常");
        return null;
    }
}

/**
* 推送一个列表
* @param pushContent 推送内容(JSON{title:'标题',content:'内容',payload:'携带参数'})
* @param type 类型【1.设备id(clientId) 2.别名】
* @param list 类型值(clientId/别名)
* @return
*/
public static Map pushMessageToList(String pushContent, int type, List<String> list) {
    /*透传消息模版*/ 
    AbstractTemplate template = getTransmissionTemplate(pushContent);
    ListMessage message = new ListMessage();
    message.setData(template);
    // 设置消息离线,并设置离线时间
    message.setOffline(true);
    // 离线有效时间,单位为毫秒,可选
    message.setOfflineExpireTime(24 * 1000 * 3600);
    message.setPriority(1);
    String taskId = igtPush.getContentId(message);
    // 配置推送目标 
    List targets = new ArrayList();
    for (int i = 0; i < list.size(); i++) {
        String cid = list.get(i);
        Target target = new Target();
        target.setAppId(appId);
        if (type == 1) {
            target.setClientId(cid);
        } else {
            target.setAlias(cid);
        }
        targets.add(target);
    }
    IPushResult ret = null;
    try {
        ret = igtPush.pushMessageToList(taskId, targets);
        log.info("is pushMessageToList: {}", ret.getResponse());
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (ret != null) {
        return ret.getResponse();
    } else {
        log.error("个推推送一个列表服务器响应异常");
        return null;
    }
}

/**
* 推送所有手机用户
* @param pushContent 推送内容(JSON{title:'标题',content:'内容',payload:'携带参数'})
* @return
*/
public static Map pushMessageToApp(String pushContent) {
    /*透传消息模版*/ 
    AbstractTemplate template = getTransmissionTemplate(pushContent);
    // 单推消息类型 
    AppMessage message = new AppMessage();
    message.setData(template);
    message.setOffline(true);
    message.setOfflineExpireTime(24 * 1000 * 3600);
    message.setSpeed(100);
    List<String> appIdList = new ArrayList<String>();
    appIdList.add(appId);
    message.setAppIdList(appIdList);
    IPushResult ret = null;
    try {
        ret = igtPush.pushMessageToApp(message);
        log.info("is pushMessageToApp res: {}", ret.getResponse());
    } catch (RequestException e) {
        e.printStackTrace();
        ret = igtPush.pushMessageToApp(message, e.getRequestId());
    }
    if (ret != null) {
        return ret.getResponse();
    } else {
        log.error("个推推送所有手机用户服务器响应异常");
        return null;
    }
}
    
/**
* 透传消息模版
* @param pushContent 透传内容
* @return
*/
private static TransmissionTemplate getTransmissionTemplate(String pushContent) {
    TransmissionTemplate template = new TransmissionTemplate();
    /*设置APPID与APPKEY*/
    template.setAppId(appId);
    template.setAppkey(appKey);
    /*透传消息设置,1为强制启动应用,客户端接收到消息后就会立即启动应用;2为等待应用启动*/
    template.setTransmissionType(2);
    template.setTransmissionContent(pushContent);
    // 解析透传内容 
    Map push = JSON.parseObject(pushContent);
    String title = Convert.toStr(push.get("title"));
    String content = Convert.toStr(push.get("content"));
    String payload = Convert.toStr(push.get("payload"));
    /*ios消息推送*/
    template.setAPNInfo(getAPNPayload(title, content, payload));
    return template;
}
    
/**
* iOS通知样式设置
* @param title
* @param content
* @param payload
* @return
*/
private static APNPayload getAPNPayload(String title, String content, String payload) {
    APNPayload apnPayload = new APNPayload();
    apnPayload.setContentAvailable(1);
    APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
    alertMsg.setTitle(title);
    alertMsg.setBody(content);
    apnPayload.setAlertMsg(alertMsg);
    apnPayload.addCustomMsg("payload", payload);
    return apnPayload;
}
    
//测试
public static void main(String[] args) {
    Map map = new HashMap();
    map.put("title", "早上好!");
    map.put("content", "你有新的消息,请及时查看");
    //打开通知消息,跳转路径
    map.put("payload", "/pages/notice/noticeList");
    String pushContent = JSON.toJSONString(map);
    pushMessageToSingle(pushContent, 2, "202011051311");
}

推送控制器:

为用户绑定别名:(一般登录后 获取用户信息时调用)

@PostMapping("/api/bindAlias")
public Results bindAlias(@RequestParam("clientId") String clientId){
    log.info("设备标识clientId:{}", clientId);
    //登录用户id 
    String userId = "202011051311";
    //绑定别名 
    Boolean b = GeTuiPush.bindAlias(clientId, userId);
    if(b){
        return new Results();
    }else{
        return new Results(400, "绑定异常!");
    }
}

uni-app

app.vue

onLaunch: function() {
    //获取系统信息
    uni.getSystemInfo({
        success: function(e) {
            // #ifdef APP-PLUS 
            //获取clientid 
            this.timer = setInterval(() => {
                let clientid = plus.push.getClientInfo().clientid;
                if (clientid && clientid != 'null') {
                    clearInterval(this.timer);
                    this.timer = null;
                    //缓存设备标识clientid
                    uni.setStorageSync('CLIENT_ID', clientid);
                }
            }, 50);
            // #endif
        }
    })
}

login.vue

/**登录成功后绑定别名*/
//用户绑定别名
var clientId = uni.getStorageSync("CLIENT_ID");//获取设备标识
let bindAlias = await this.$u.api.bindAlias({
    clientId: clientId
})

监听点击消息,放到index.vue页面

onLoad() {
    // #ifdef APP-PLUS 
    /* 监听 - 点击推送通知消息 */
    plus.push.addEventListener('click', msg => {
    //msg.payload 跳转路径
    uni.navigateTo({
        url: msg.payload
    });
});
// #endif