APP消息推送 个推消息推送 实例代码

APP消息推送 个推消息推送 实例代码


极光推送示例链接: https://blog.csdn.net/qq_36992948/article/details/110129927
pom文件增加

<!--注意查看setting.xml文件的中央存储库冲突-->
    <repositories>
        <repository>
            <id>nexuss-aliyun</id>
            <url>http://maven.aliyun.com/nexus/content/groups/public</url>
        </repository>
        <repository>
            <id>getui-nexus</id>
            <url>http://mvn.gt.getui.com/nexus/content/repositories/releases/</url>
        </repository>
        <repository>
            <id>alimaven</id>
            <url>https://maven.aliyun.com/repository/public</url>
        </repository>
    </repositories>

controller文件

/**
 * 描述:
 * 个推消息推送
 * @author cmw
 * @create 2020/6/22 11:29
 */
@Slf4j
@RequestMapping("/getui")
@Controller
public class GetuiController {

    @Autowired
    private GetuiService getuiService;


    @Value("${getui.strategyJson:}")
    String strategyJson;//厂商推送指令

    //个推 key
 @Value("${getui.appId:}")
    String appId;
    @Value("${getui.appKey:}")
    String appKey;
    @Value("${getui.masterSecret:}")
    String masterSecret;
    @Value("${getui.getuiUrl:}")
    String getuiUrl;
    @Value("${getui.android.intent:}")
    private String intent;
    
    /**
     * app登录时进行判断是否已经注册到个推
     * @param openid
     * @return
     */
    @GetMapping("/bindAliasByApp")
    @ResponseBody
    public Map loginByApp(String openid,String clientId){
        log.info("【韩国APP 个推消息推送】参数: openid={},clientId={}",openid,clientId);
        Map result = new HashMap();
        result.put("code","1");
        try {
            if(!VerifyData.strIsNotNull(openid)){
                result.put("code","1");
                result.put("msg","参数错误-openId");
                return result;
            }
            if(!VerifyData.strIsNotNull(clientId)){
                result.put("code","2");
                result.put("msg","参数错误-clientId");
                return result;
            }
            log.info("参数 url={},appkey={},masterSecret={},appId={}",getuiUrl,appKey,masterSecret,appId);
            IGtPush push = new IGtPush(getuiUrl, appKey,masterSecret);
            IAliasResult aliasResult = push.queryClientId(appId, openid);
            log.info("aliasResult="+JSONObject.toJSONString(aliasResult));
            IAliasResult bindAlias = null;
            IAliasResult unbindAlias = null;
            if (aliasResult != null) {
                if (aliasResult.getResult()) {
                    boolean isBind = false;
                    for (String cid : aliasResult.getClientIdList()) {
                        if (clientId.equals(cid)) {
                            isBind = true;
                        } else {
                            unbindAlias = push.unBindAlias(appId, openid, cid);
                            log.info("个推解绑别名result1={}", JSONObject.toJSONString(unbindAlias));
                        }
                    }
                    if (!isBind) {
                        bindAlias = push.bindAlias(appId, openid, clientId);
                        log.info("个推绑定别名result2={}", JSONObject.toJSONString(bindAlias));
                    }
                } else {
                    bindAlias = push.bindAlias(appId, openid, clientId);
                    log.info("个推绑定别名result3={}", JSONObject.toJSONString(bindAlias));
                }
                if(bindAlias!=null && !bindAlias.getResult()){
                    result.put("code","5");
                    result.put("data",bindAlias.getResponse());
                    result.put("msg","绑定失败");
                    return result;
                }
            }
            result.put("code","3");
            result.put("msg","绑定成功");
            return result;
        }catch (Exception e){
            log.error("【APP 个推消息推送】异常",e.getMessage());
            result.put("code","4");
            result.put("msg","系统异常");
        }
        return result;
    }

    /**
     * app归还订单
     * @param openid
     * @return
     */
    @GetMapping("/sendPushMsg")
    @ResponseBody
    public String sendPush_getui(String openid) {
        try {
            IGtPush push = new IGtPush(getuiUrl, appKey, masterSecret);

            Map returnModel = getuiService.getReturnModel();
            if(returnModel==null||returnModel.size()==0){
                throw new Exception("查无归还模板消息");
            }
            String title = String.valueOf(returnModel.get("title"));
            String content = String.valueOf(returnModel.get("content"));
            //return this.send_toList(openid,title,content,"");
            AbstractNotifyStyle style = getStyle6(title,content,"");
            AbstractTemplate template = new AbstractTemplate();
           		 template = getNotificationTemplate(style,title,content);//通知模板 跳转app首页
               // template = getActivityTemplate(style, title, content, intent);//【通知模板】打开应用内页面
               //template = getTemplate(title,content);//透传模板
            // STEP5:定义"AppMessage"类型消息对象,设置推送消息有效期等推送参数
            SingleMessage message = new SingleMessage();
            message.setData(template);
            message.setOffline(true);
            message.setOfflineExpireTime(24 * 3600 * 1000);  // 离线有效时间,时间单位为毫秒
            // 可选,1为wifi,0为不限制网络环境。根据手机处于的网络情况,决定是否下发
            message.setPushNetWorkType(0);
            // 厂商通道下发策略
            message.setStrategyJson(strategyJson);
            Target target = new Target();
            target.setAppId(GetuiConstant.appId);
            target.setAlias(openid);//别名
            // STEP6:执行推送
            IPushResult ret = null;
            ret = push.pushMessageToSingle(message, target);
            if (ret != null) {
                log.info(ret.getResponse().toString());
                return ret.getResponse().toString();
            } else {
                log.info("服务器响应异常");
            }
        } catch (Exception e) {
            log.error("【个推APP消息发送】异常",e);
            return "";
            //ret = push.pushMessageToSingle(message, target, e.getRequestId());
        }
        return "";
    }

    /**
     * 根据APPId进行整体推送(推送给APP所有用户)
     * @param title
     * @param content
     * @return
     */
    @PostMapping(value = "/send_toApp")
    @ResponseBody
    public String send_toApp(String title,String content,String url){
        IGtPush push = new IGtPush(getuiUrl, appKey, masterSecret);
        AbstractNotifyStyle style = getStyle6(title,content,url);
        NotificationTemplate template = getNotificationTemplate(style,title,content);
        //TransmissionTemplate template = getTemplate(title,content);
        AppMessage message = new AppMessage();
        message.setData(template);
        message.setOffline(true);
        // 离线有效时间,单位为毫秒
        message.setOfflineExpireTime(24 * 1000 * 3600);
        // 厂商通道下发策略
        message.setStrategyJson(strategyJson);

        List<String> appList = new ArrayList<>();
        appList.add(appId);
        message.setAppIdList(appList);
        IPushResult ret = null;
        try {
            ret = push.pushMessageToApp(message, System.currentTimeMillis()+"_toApp");
        } catch (RequestException e) {
            e.printStackTrace();
        }
        if (ret != null) {
            log.info(ret.getResponse().toString());
            return ret.getResponse().toString();
        } else {
            log.info("服务器响应异常");
        }
        return "";
    }

    /**
     * 根据APPId进行批量推送
     * @param openids openid 列表
     * @param title 标题
     * @param content 内容
     * @return
     */
    @PostMapping(value = "/send_toList")
    @ResponseBody
    public String send_toList(String openids,String title,String content,String url){
        List<String> openidList = new ArrayList<>();
        if(openids.indexOf(",")!=-1){
            String[] idArr = openids.split(",");
            for(String id:idArr){
                openidList.add(id);
            }
        }else{
            openidList.add(openids);
        }
        IGtPush push = new IGtPush(getuiUrl, appKey, masterSecret);
        AbstractNotifyStyle style = getStyle6(title,content,url);
        NotificationTemplate template = getNotificationTemplate(style,title,content);
        //TransmissionTemplate template = getTemplate(title,content);
        ListMessage message = new ListMessage();
        message.setData(template);
        message.setOffline(true);
        // 离线有效时间,单位为毫秒
        message.setOfflineExpireTime(24 * 1000 * 3600);
        // 厂商通道下发策略
        message.setStrategyJson(strategyJson);

        // 配置推送目标
        List<Target> targets = new ArrayList<>();
        for(String openid:openidList){
            Target target = new Target();
            target.setAppId(appId);
            target.setAlias(openid);
            targets.add(target);
        }
        // taskId用于在推送时去查找对应的message
        String taskId = push.getContentId(message);

        IPushResult ret = null;
        try {
            ret = push.pushMessageToList(taskId, targets);
        } catch (RequestException e) {
            e.printStackTrace();
        }
        if (ret != null) {
            log.info(ret.getResponse().toString());
            return ret.getResponse().toString();
        } else {
            log.info("服务器响应异常");
        }
        return "";
    }

    //普通文本显示(一行)
    private AbstractNotifyStyle getStyle0(String title,String content){
        Style0 style = new Style0();
        // STEP2:设置推送标题、推送内容
        style.setTitle(title);
        style.setText(content);
        //style.setLogo(GetuiConstant.logo);  // 设置推送图标
        //style.setLogoUrl(GetuiConstant.logo);//设置通知栏网络图标
        // STEP3:设置响铃、震动等推送效果
        style.setRing(true);  // 设置响铃
        style.setVibrate(true);  // 设置震动
        //style.setBadgeAddNum(1);// 角标, 必须大于0, 个推通道下发有效; 此属性目前仅针对华为 EMUI 4.1 及以上设备有效
        return style;
    }

    //长文本或(大图+短文本)显示
    private AbstractNotifyStyle getStyle6(String title,String content,String url){
        Style6 style = new Style6();
        // STEP2:设置推送标题、推送内容
        style.setTitle(title);
        style.setText(content);//短文本
        //style.setLogo(GetuiConstant.logo);  // 设置推送图标
        //style.setLogoUrl(GetuiConstant.logo);//设置通知栏网络图标
        style.setBigStyle2(content);//长文本
        if(VerifyData.strIsNotNull(url)){
            style.setBigStyle1(url);//通知展示大图样式,参数是大图的URL地址
        }

        return style;
    }

    //推送模板
    private NotificationTemplate getNotificationTemplate(AbstractNotifyStyle style,String title, String content){
        // STEP4:选择通知模板
        NotificationTemplate template = new NotificationTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setStyle(style);
        template.setTransmissionContent("{title:\""+title+"\",content:\""+content+"\",payload:\"自定义数据\"}"); //透传内容
        template.setAPNInfo(getAPNPayload(title,content));
        return template;
    }

    //【通知模板】打开应用内页面
    private StartActivityTemplate getActivityTemplate(AbstractNotifyStyle style,String title, String content,String intent) {
        StartActivityTemplate template = new StartActivityTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setIntent(intent);
        template.setStyle(style);
        template.setAPNInfo(getAPNPayload(title,content)); //ios消息推送
        return template;
    }

    //透传模板
    private TransmissionTemplate getTemplate(String title,String content) {
        TransmissionTemplate template = new TransmissionTemplate();
        template.setAppId(appId);
        template.setAppkey(appKey);
        template.setTransmissionType(2);
        template.setTransmissionContent("{title:\""+title+"\",content:\""+content+"\",payload:\"自定义数据\"}"); //透传内容
        template.setAPNInfo(getAPNPayload(title,content)); //ios消息推送
        return template;
    }

    //ios apns
    private APNPayload getAPNPayload(String title,String content) {
        APNPayload payload = new APNPayload();
        //在已有数字基础上加1显示,设置为-1时,在已有数字上减1显示,设置为数字时,显示指定数字
        payload.setAutoBadge("0");
        payload.setAlertMsg(getDictionaryAlertMsg(title,content));
        //payload.setAlertMsg(new APNPayload.SimpleAlertMsg(GetuiConstant.content));
        return payload;
    }

    //ios apns
    private APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(String title,String content) {
        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
        alertMsg.setBody(content);
        alertMsg.setTitle(title);
        return alertMsg;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值