admin
2019-07-09 531d93708df8017e59830f15b41f3cc42d6126e6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package com.yeshi.fanli.util.push;
 
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.List;
import java.util.Properties;
 
import javax.annotation.PostConstruct;
 
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yeshi.utils.annotation.MapUtil;
 
import com.alibaba.fastjson.JSONObject;
import com.yeshi.fanli.entity.config.push.HWPushConfig;
import com.yeshi.fanli.exception.PushException;
import com.yeshi.fanli.service.inter.config.BusinessSystemService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.taobao.TaoBaoUtil;
 
import net.sf.json.JSONArray;
 
@Component
public class HWPushUtil {
 
    private static HWPushUtil hWPushUtil;
 
    @Autowired
    private BusinessSystemService businessSystemService;
 
    @PostConstruct
    public void init() {
        hWPushUtil = this;
        hWPushUtil.businessSystemService = this.businessSystemService;
    }
 
    private static String appSecret = "";
    private static String appId = "";// 用户在华为开发者联盟申请的appId和appSecret(会员中心->我的产品,点击产品对应的Push服务,点击“移动应用详情”获取)
    private static String tokenUrl = "https://login.cloud.huawei.com/oauth2/v2/token"; // 获取认证Token的URL
    private static String apiUrl = "https://api.push.hicloud.com/pushsend.do"; // 应用级消息下发API
    private static String accessToken;// 下发通知消息的认证Token
    private static long tokenExpiredTime; // accessToken的过期时间
 
    static {
        Properties ps = org.yeshi.utils.PropertiesUtil
                .getProperties(TaoBaoUtil.class.getClassLoader().getResourceAsStream("push_hw.properties"));
        HWPushConfig config = (HWPushConfig) MapUtil.parseMap(HWPushConfig.class, ps);
        appId = config.getAppId();
        appSecret = config.getAppSecret();
    }
 
    /**
     * 推送商品
     * 
     * @param deviceTokens
     *            -最大值1000
     * @param title
     * @param content
     * @param goodsType
     * @param goodsId
     * @throws PushException
     */
    public static void pushGoods(List<String> deviceTokens, String title, String content, int goodsType, Long goodsId)
            throws PushException {
        if (deviceTokens != null && deviceTokens.size() > 1000)
            throw new PushException(1, "设备数不能超过1000个");
 
        String activity = Constant.systemCommonConfig.getAndroidBaseactivityName()
                + ".ui.recommend.GoodsBrowserActivity";
        activity = activity.replace(Constant.systemCommonConfig.getAndroidPackageName(),
                Constant.systemCommonConfig.getAndroidPackageName() + "/");
 
        String intent = "intent:#Intent;launchFlags=0x4000000;component=" + activity + ";S.id=" + goodsId + ";end";
        try {
            String result = sendPushHWMessageForIntent(deviceTokens, title, content, intent);
            net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(result);
            if (!"success".equalsIgnoreCase(data.optString("msg")))
                throw new PushException(2, result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 网页推送
     * 
     * @param deviceTokens
     *            最大值1000
     * @param title
     * @param content
     * @param url
     *            -网页链接
     * @throws PushException
     */
    public static void pushWeb(List<String> deviceTokens, String title, String content, String url)
            throws PushException {
        if (deviceTokens != null && deviceTokens.size() > 1000)
            throw new PushException(1, "设备数不能超过1000个");
 
        String activity = Constant.systemCommonConfig.getAndroidBaseactivityName() + ".ui.invite.ShareBrowserActivity";
        activity = activity.replace(Constant.systemCommonConfig.getAndroidPackageName(),
                Constant.systemCommonConfig.getAndroidPackageName() + "/");
 
        String intent = "intent:#Intent;launchFlags=0x4000000;component=" + activity + ";S.url="
                + URLEncoder.encode(url) + ";end";
        try {
            String result = sendPushHWMessageForIntent(deviceTokens, title, content, intent);
            net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(result);
            if (!"success".equalsIgnoreCase(data.optString("msg")))
                throw new PushException(2, result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 站内信推送
     * 
     * @param deviceTokens
     *            最大值1000
     * @param title
     * @param content
     * @param url
     *            -网页链接
     * @throws PushException
     */
    public static void pushZNX(List<String> deviceTokens, String title, String content) throws PushException {
        if (deviceTokens != null && deviceTokens.size() > 1000)
            throw new PushException(1, "设备数不能超过1000个");
 
        String activity = Constant.systemCommonConfig.getAndroidBaseactivityName() + ".ui.mine.AppMailActivity";
        activity = activity.replace(Constant.systemCommonConfig.getAndroidPackageName(),
                Constant.systemCommonConfig.getAndroidPackageName() + "/");
 
        String intent = "intent:#Intent;launchFlags=0x4000000;component=" + activity + ";end";
        try {
            String result = sendPushHWMessageForIntent(deviceTokens, title, content, intent);
            net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(result);
            if (!"success".equalsIgnoreCase(data.optString("msg")))
                throw new PushException(2, result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 推送简单文字
     * 
     * @param deviceTokens
     * @param title
     * @param content
     * @throws PushException
     */
 
    public static void pushSimpleText(List<String> deviceTokens, String title, String content) throws PushException {
        if (deviceTokens != null && deviceTokens.size() > 1000)
            throw new PushException(1, "设备数不能超过1000个");
        try {
            String result = sendPushHWMessageForOpenApp(deviceTokens, title, content);
            net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(result);
            if (!"success".equalsIgnoreCase(data.optString("msg")))
                throw new PushException(2, result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 推送设备消息
     * 
     * @param deviceTokens
     *            -最大1000条
     * @param title
     *            -标题
     * @param content
     *            -内容
     * @param intent
     *            如:intent:#Intent;component=com.yeshi.ec.rebate/.myapplication.
     *            ui.invite.ShareBrowserActivity;S.url="+URLEncoder.encode("http
     *            ://www.baidu.com")+";end
     * @return
     * @throws IOException
     */
    private static String sendPushHWMessageForIntent(List<String> deviceTokens, String title, String content,
            String intent) throws IOException {
        if (tokenExpiredTime <= System.currentTimeMillis()) {
            refreshToken();
        }
 
        /* PushManager.requestToken为客户端申请token的方法,可以调用多次以防止申请token失败 */
        /* PushToken不支持手动编写,需使用客户端的onToken方法获取 */
        JSONArray deviceTokenList = new JSONArray();// 目标设备Token
        for (String deviceToken : deviceTokens) {
            deviceTokenList.add(deviceToken);
        }
 
        // 仅通知栏消息需要设置标题和内容,透传消息key和value为用户自定义
        JSONObject body = new JSONObject();
        body.put("title", title);// 消息标题
        body.put("content", content);// 消息内容体
 
        // 定义需要打开的appPkgName
        JSONObject param = new JSONObject();
 
        param.put("intent", intent);
 
        JSONObject action = new JSONObject();
        action.put("type", 1);// (1 自定义行为:行为由参数intent定义;2 打开URL:URL地址由参数url定义;3
                                // 打开APP:默认值,打开App的首页)
        action.put("param", param);// 消息点击动作参数
 
        JSONObject msg = new JSONObject();
        msg.put("type", 3);// 3: 通知栏消息,异步透传消息请根据接口文档设置
        msg.put("action", action);// 消息点击动作
        msg.put("body", body);// 通知栏消息body内容
 
        // 扩展信息,含BI消息统计,特定展示风格,消息折叠。
        JSONObject ext = new JSONObject();
        ext.put("biTag", "Trump");// 设置消息标签,如果带了这个标签,会在回执中推送给CP用于检测某种类型消息的到达率和状态
        // ext.put("icon",
        // "http://pic.qiantucdn.com/58pic/12/38/18/13758PIC4GV.jpg");//
        // 自定义推送消息在通知栏的图标,value为一个公网可以访问的URL
 
        // 华为PUSH消息总结构体
        JSONObject hps = new JSONObject();
        hps.put("msg", msg);
        hps.put("ext", ext);
 
        JSONObject payload = new JSONObject();
        payload.put("hps", hps);
 
        String postBody = MessageFormat.format(
                "access_token={0}&nsp_svc={1}&nsp_ts={2}&device_token_list={3}&payload={4}",
                URLEncoder.encode(accessToken, "UTF-8"), URLEncoder.encode("openpush.message.api.send", "UTF-8"),
                URLEncoder.encode(String.valueOf(System.currentTimeMillis() / 1000), "UTF-8"),
                URLEncoder.encode(deviceTokenList.toString(), "UTF-8"), URLEncoder.encode(payload.toString(), "UTF-8"));
 
        String postUrl = apiUrl + "?nsp_ctx="
                + URLEncoder.encode("{\"ver\":\"1\", \"appId\":\"" + appId + "\"}", "UTF-8");
        String result = httpPost(postUrl, postBody, 5000, 5000);
 
        return result;
    }
 
    /**
     * 推送打开APP的消息
     * 
     * @param deviceTokens
     * @param title
     * @param content
     * @return
     * @throws IOException
     */
    private static String sendPushHWMessageForOpenApp(List<String> deviceTokens, String title, String content)
            throws IOException {
        if (tokenExpiredTime <= System.currentTimeMillis()) {
            refreshToken();
        }
 
        /* PushManager.requestToken为客户端申请token的方法,可以调用多次以防止申请token失败 */
        /* PushToken不支持手动编写,需使用客户端的onToken方法获取 */
        JSONArray deviceTokenList = new JSONArray();// 目标设备Token
        for (String deviceToken : deviceTokens) {
            deviceTokenList.add(deviceToken);
        }
 
        // 仅通知栏消息需要设置标题和内容,透传消息key和value为用户自定义
        JSONObject body = new JSONObject();
        body.put("title", title);// 消息标题
        body.put("content", content);// 消息内容体
 
        // 定义需要打开的appPkgName
        JSONObject param = new JSONObject();
 
        JSONObject action = new JSONObject();
        action.put("type", 3);// (1 自定义行为:行为由参数intent定义;2 打开URL:URL地址由参数url定义;3
                                // 打开APP:默认值,打开App的首页)
        action.put("param", param);// 消息点击动作参数
 
        JSONObject msg = new JSONObject();
        msg.put("type", 3);// 3: 通知栏消息,异步透传消息请根据接口文档设置
        msg.put("action", action);// 消息点击动作
        msg.put("body", body);// 通知栏消息body内容
 
        // 扩展信息,含BI消息统计,特定展示风格,消息折叠。
        JSONObject ext = new JSONObject();
        ext.put("biTag", "Trump");// 设置消息标签,如果带了这个标签,会在回执中推送给CP用于检测某种类型消息的到达率和状态
        // ext.put("icon",
        // "http://pic.qiantucdn.com/58pic/12/38/18/13758PIC4GV.jpg");//
        // 自定义推送消息在通知栏的图标,value为一个公网可以访问的URL
 
        // 华为PUSH消息总结构体
        JSONObject hps = new JSONObject();
        hps.put("msg", msg);
        hps.put("ext", ext);
 
        JSONObject payload = new JSONObject();
        payload.put("hps", hps);
 
        String postBody = MessageFormat.format(
                "access_token={0}&nsp_svc={1}&nsp_ts={2}&device_token_list={3}&payload={4}",
                URLEncoder.encode(accessToken, "UTF-8"), URLEncoder.encode("openpush.message.api.send", "UTF-8"),
                URLEncoder.encode(String.valueOf(System.currentTimeMillis() / 1000), "UTF-8"),
                URLEncoder.encode(deviceTokenList.toString(), "UTF-8"), URLEncoder.encode(payload.toString(), "UTF-8"));
 
        String postUrl = apiUrl + "?nsp_ctx="
                + URLEncoder.encode("{\"ver\":\"1\", \"appId\":\"" + appId + "\"}", "UTF-8");
        String result = httpPost(postUrl, postBody, 5000, 5000);
 
        return result;
    }
 
    /**
     * 
     * 方法说明: 获取下发通知消息的认证Token
     * 
     * @author mawurui createTime 2018年5月14日 下午4:47:26
     * @throws IOException
     */
    private static void refreshToken() throws IOException {
        String msgBody = MessageFormat.format("grant_type=client_credentials&client_secret={0}&client_id={1}",
                URLEncoder.encode(appSecret, "UTF-8"), appId);
        String response = httpPost(tokenUrl, msgBody, 5000, 5000);
        JSONObject obj = JSONObject.parseObject(response);
        accessToken = obj.getString("access_token");
        tokenExpiredTime = System.currentTimeMillis() + obj.getLong("expires_in") * 1000 - 5 * 60 * 1000;
    }
 
    public static String httpPost(String httpUrl, String data, int connectTimeout, int readTimeout) throws IOException {
        OutputStream outPut = null;
        HttpURLConnection urlConnection = null;
        InputStream in = null;
 
        try {
            URL url = new URL(httpUrl);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            urlConnection.setConnectTimeout(connectTimeout);
            urlConnection.setReadTimeout(readTimeout);
            urlConnection.connect();
 
            // POST data
            outPut = urlConnection.getOutputStream();
            outPut.write(data.getBytes("UTF-8"));
            outPut.flush();
 
            if (urlConnection.getResponseCode() < 400) {
                in = urlConnection.getInputStream();
            } else {
                in = urlConnection.getErrorStream();
            }
 
            List<String> lines = IOUtils.readLines(in, urlConnection.getContentEncoding());
            StringBuffer strBuf = new StringBuffer();
            for (String line : lines) {
                strBuf.append(line);
            }
            System.out.println(strBuf.toString());
            return strBuf.toString();
        } finally {
            IOUtils.closeQuietly(outPut);
            IOUtils.closeQuietly(in);
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
}