xuhy
2025-01-09 712f70b2936079a131ecb1e63c6d337171618cad
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
package com.stylefeng.guns.core.util;
 
import com.alibaba.fastjson.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
 
 
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * @program: openPlatform
 * @description: 下单
 */
 
public class AppOrder {
    static String appId = "10037e6f66f2d0f901672aa27d690006";
    static String appKey = "47ace12ae3b348fe93ab46cee97c6fde";
    static String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
    static String nonce = UUID.randomUUID().toString().replace("-", "");
    static String authorization;
    static String mid="898201612345678";
    static String tid="00000001";
 
 
    public static void main(String[] args) throws Exception {
        placeAnOrder(new BigDecimal(1));
    }
 
 
    /**
     * app下单
     *money 分
     * @throws Exception
     */
    public static void placeAnOrder(BigDecimal amount) throws Exception {
        JSONObject json = new JSONObject();
        json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));    // 报文请求时间
        json.put("merOrderId", Util.getMerchantOrderId()); // 商户订单号
        json.put("mid", "898340149000005"); // 商户号
        json.put("tid", "88880001");    // 终端号
        json.put("instMid", "APPDEFAULT"); // 业务类型
        json.put("totalAmount", Integer.valueOf(String.valueOf(amount.multiply(new BigDecimal("100")))));      // 支付总金额
        json.put("orderDesc", "");
        json.put("subAppId", "wxasdasdasdasdads");
        json.put("notifyUrl", "https://www.baidu.com");
        json.put("tradeType", "APP");  // 交易类型,微信必传
        //  json.put("divisionFlag", true); // 分账标记
        //  json.put("platformAmount", 0); // 平台商户分账金额
//        ArrayList<JSONObject> subOrders = new ArrayList<>();
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("mid", "988460101800201");
//        jsonObject.put("totalAmount", 1);
//        subOrders.add(jsonObject);
        //    json.put("subOrders", subOrders);
 
        System.err.println("请求报文json:\n" + json);
        String url = "https://test-api-open.chinaums.com/v1/netpay/uac/app-order";
 
        //OPEN-BODY-SIG 方式
        String authorization = GetOpenBodySig.getOpenBodySig(appId, appKey, json.toString());
        //token 方式
//        String authorization = GetAccessToken.getToken();
        String send = GetOpenBodySig.sendToken(url, json.toString(), authorization);
        System.err.println("响应报文json:\n" + send);
    }
 
 
    /**
     * open-body-sig方式获取到Authorization 的值
     *
     * @param appId  f0ec96ad2c3848b5b810e7aadf369e2f
     * @param appKey 775481e2556e4564985f5439a5e6a277
     * @param body   json字符串 String body = "{\"merchantCode\":\"123456789900081\",\"terminalCode\":\"00810001\",\"merchantOrderId\":\"20123333644493200\",\"transactionAmount\":\"1\",\"merchantRemark\":\"测试\",\"payMode\":\"CODE_SCAN\",\"payCode\":\"285668667587422761\",\"transactionCurrencyCode\":\"156\"}";
     * @return
     * @throws Exception
     */
    public static String getOpenBodySig(String appId, String appKey, String body) throws Exception {
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String nonce = UUID.randomUUID().toString().replace("-", "");
        byte[] data = body.getBytes("UTF-8");
        System.out.println("data:\n" + body);
        InputStream is = new ByteArrayInputStream(data);
        String bodyDigest = DigestUtils.sha256Hex(is);
        System.out.println("bodyDigest:\n" + bodyDigest);
        String str1_C = appId + timestamp + nonce + bodyDigest;
 
        System.out.println("str1_C:" + str1_C);
        byte[] localSignature = hmacSHA256(str1_C.getBytes(), appKey.getBytes());
 
        String localSignatureStr = Base64.encodeBase64String(localSignature);   // Signature
        System.out.println("Authorization:\n" + "OPEN-BODY-SIG AppId=" + "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce=" + "\"" + nonce + "\"" + ", Signature=" + "\"" + localSignatureStr + "\"\n");
        return ("OPEN-BODY-SIG AppId=" + "\"" + appId + "\"" + ", Timestamp=" + "\"" + timestamp + "\"" + ", Nonce=" + "\"" + nonce + "\"" + ", Signature=" + "\"" + localSignatureStr + "\"");
    }
 
 
    public static String getToken() throws Exception {
        JSONObject jsonObject = new JSONObject();
        String all = appId + timestamp + nonce + appKey;
        String signature = DigestUtils.sha256Hex(getMessageBytes(all));
        jsonObject.put("appId", appId);
        jsonObject.put("timestamp", timestamp);
        jsonObject.put("nonce", nonce);
        jsonObject.put("signature", signature);
        jsonObject.put("signMethod", "SHA256");
        String response = send("https://test-api-open.chinaums.com/v1/token/access", jsonObject.toString(), "");
        com.alibaba.fastjson.JSONObject respJson = JSON.parseObject(response.toString());
        String accessToken = respJson.get("accessToken").toString();
        accessToken = "OPEN-ACCESS-TOKEN AccessToken=" + accessToken + "";
        System.out.println("Authorization:\n" + accessToken);
        return accessToken;
    }
 
 
    /**
     * @param data
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static byte[] hmacSHA256(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data);
    }
 
    public static String send(String u, String entity, String authorization) throws Exception {
 
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream out = null;
        BufferedReader br = null;
        String resultStr = null;
        Map<String, String> resultMap = new HashMap<String, String>();
 
        try {
 
            javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
 
 
                public boolean verify(String hostname,
                                      SSLSession sslsession) {
                    return true;
                }
            });
 
            URL url = new URL(u);
            if ("https".equalsIgnoreCase(url.getProtocol())) {
                SslUtils.ignoreSsl();
            }
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Authorization", authorization);
            connection.setRequestProperty("Accept_Charset", "UTF-8");
            connection.setRequestProperty("Content-Type", "application/json");
            //发送POST请求参数
            out = connection.getOutputStream();
            out.write(entity.getBytes("UTF-8"));
            out.flush();
 
            StringBuffer sbf = new StringBuffer();
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String temp = null;
                // 循环遍历一行一行读取数据
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
            } else {
                try {
                    is = connection.getErrorStream();
                    // 对输入流对象进行包装:charset根据工作项目组的要求来设置
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    // 循环遍历一行一行读取数据
                    while ((temp = br.readLine()) != null) {
                        sbf.append(temp);
                        sbf.append("\r\n");
                    }
                    resultStr = sbf.toString();
 
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            resultStr = sbf.toString();
            System.out.println("resultStr:" + resultStr);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("errCode", "HttpURLException");
            resultMap.put("msg", "调用银商接口出现异常:" + e.toString());
            resultStr = JSONObject.fromObject(resultMap).toString();
            //return resultStr;
        } finally {
            if (out != null) {
                out.close();
            }
            connection.disconnect();
        }
 
        return resultStr;
 
    }
 
    public static byte[] getMessageBytes(String message) {
        try {
            return message.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("签名过程中出现错误");
        }
    }
 
    public static String getMerchantOrderId() {
        return DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS") + RandomStringUtils.randomNumeric(7);
    }
}