获取华为token、华为推送

2022-02-19  本文已影响0人  AC编程

一、获取华为access_token

 /**
     * 获取华为access_token
     * 文档:https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/oauth2-0000001212610981#section128682386159
     *
     * @return
     */
    private String getAccessToken() {
        String accessToken = huaWeiRdsHelper.get();
        if (StringUtil.isNotBlank(accessToken)) {
            return accessToken;
        }

        try {
            String requestBody = MessageFormat.format("grant_type=client_credentials&client_secret={0}&client_id={1}", appSecret, appId);

            HttpPost httpPost = new HttpPost("https://oauth-login.cloud.huawei.com/oauth2/v3/token");
            StringEntity entity = new StringEntity(requestBody);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);
            String jsonStr = EntityUtils.toString(response.getEntity());
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == SUCCESS_CODE) {
                JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                accessToken = jsonObject.getString("access_token");
                huaWeiRdsHelper.add(accessToken);
                return accessToken;
            } else {
                log.error("获取华为推送access_token失败");
            }
        } catch (IOException e) {
            log.error("获取华为推送access_token失败,异常:{}", e.getMessage());
        }
        return null;
    }

二、华为推送组装参数

/**
     * 华为推送
     * 文档:https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/android-server-dev-0000001050040110
     * 参数说明:https://developer.huawei.com/consumer/cn/doc/development/HMSCore-References/https-send-api-0000001050986197#section8686112674319
     * 官方样例:https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Examples/server-sample-code-0000001050986079
     *
     * @param pushNotificationVO
     * @return
     */
    @Override
    public Boolean pushNotification(PushNotificationVO pushNotificationVO, MemberDevice memberDevice) {
        log.info("华为推送:{}", pushNotificationVO);
        log.info("华为推送,appKey,appSecret:{},{}", appId, appSecret);
        String accessToken = getAccessToken();
        if (StringUtil.isBlank(accessToken)) {
            log.error("华为推送,获取accessToken失败");
            return false;
        }

        String token = memberDevice.getToken();
        /**
         * 通知栏消息体示例
         * {
         *     "validate_only": false,
         *     "message": {
         *         "android": {
         *             "notification": {
         *                 "title": "test title",
         *                 "body": "test body",
         *                 "click_action": {
         *                     "type": 3
         *                 }
         *             }
         *         },
         *         "token": ["pushtoken1"]
         *     }
         * }
         */

        Map<String, String> extra = new LinkedHashMap();
        Map<String, Object> objectMap = BeanUtil.beanToMap(pushNotificationVO);
        objectMap.forEach((key, value) -> {
            if (null != value && !key.equals("map")) {
                extra.put(key, value.toString());
            }
        });
        if (null != pushNotificationVO.getMap()) {
            pushNotificationVO.getMap().forEach((key, value) -> {
                if (null != value) {
                    extra.put(key, value.toString());
                }
            });
        }

        Map notificationMap = new HashMap<>();
        notificationMap.put("title", pushNotificationVO.getTitle());
        notificationMap.put("body", pushNotificationVO.getBody());
        notificationMap.put("icon", pushNotificationVO.getIconUrl());
        notificationMap.put("badge", pushNotificationVO.getBadge());

        Map dataMap = new HashMap<>();
        if (extra.size() > 0) {
            dataMap.put("extra", extra);
        }

        Map androidMap = new HashMap<>();
        androidMap.put("notification", notificationMap);

        Map messageMap = new HashMap<>();
        messageMap.put("token", Arrays.asList(token));
        messageMap.put("android", androidMap);
        if (dataMap.size() > 0) {
            messageMap.put("data", dataMap);
        }

        Map pushMessageMap = new HashMap<>();
        pushMessageMap.put("validate_only", false);
        pushMessageMap.put("message", messageMap);

        log.info("pushMessageMap:{}", pushMessageMap);

        return sendRequest(pushMessageMap, accessToken);
    }

三、推送

private boolean sendRequest(Map map, String accessToken) {
        try {
            String pushUrl = MessageFormat.format("https://push-api.cloud.huawei.com/v1/{0}/messages:send", appId);
            HttpPost httpPost = new HttpPost(pushUrl);
            StringEntity entity = new StringEntity(JSON.toJSONString(map), "UTF-8");

            httpPost.setHeader("Authorization", "Bearer " + accessToken);
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == SUCCESS_CODE) {
                log.info("华为推送成功");
                return true;
            } else {
                log.error("华为推送失败,{}", statusCode);
            }
        } catch (Exception e) {
            log.error("华为推送失败,{}", e.getMessage());
            return false;
        }
        return true;
    }
上一篇下一篇

猜你喜欢

热点阅读