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 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 resultMap = new HashMap(); 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); } }