JAVA微信支付分生成签名

JAVA微信支付分生成签名

//生成签名的方法:

public class CreateSigner {

public static Map<String,Object> getToken(String method, HttpUrl url, String body) throws IOException, SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    String nonceStr = String.valueOf(UUID.randomUUID()).replace("-","");
    long timestamp = System.currentTimeMillis() / 1000;
    String message = buildMessage(method, url, timestamp, nonceStr, body);
    String signature = sign(message.getBytes(StandardCharsets.UTF_8));
    Map map=new HashMap();
    map.put("sign","mchid=""+BasicInfo.XIAO_MchId+"","
            + "nonce_str=""+nonceStr+"","
            + "timestamp=""+timestamp+"","
            + "serial_no=""+BasicInfo.XIAO_mchSerialNo+"","
            + "signature=""+signature+""");
    map.put("timestamp",timestamp);
    map.put("noncestr",nonceStr);
    return map;
}

static String sign(byte[] message) throws NoSuchAlgorithmException, IOException, InvalidKeyException, SignatureException {
    Signature sign = Signature.getInstance("SHA256withRSA");
    sign.initSign(getPrivateKey("/zdjs/weixin/apiclient_key.pem"));
    sign.update(message);

    return Base64.getEncoder().encodeToString(sign.sign());
}

static String buildMessage(String method, HttpUrl url, long timestamp, String nonceStr, String body) {
    String canonicalUrl = url.encodedPath();
    if (url.encodedQuery() != null) {
        canonicalUrl += "?" + url.encodedQuery();
    }


    System.err.println(method + "
"
            + canonicalUrl + "
"
            + timestamp + "
"
            + nonceStr + "
"
            + body + "
");
    return method + "
"
            + canonicalUrl + "
"
            + timestamp + "
"
            + nonceStr + "
"
            + body + "
";
}

public static PrivateKey getPrivateKey(String filename) throws IOException {

    String content = new String(Files.readAllBytes(Paths.get(filename)), "utf-8");
    try {
        String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
                .replace("-----END PRIVATE KEY-----", "")
                .replaceAll("\s+", "");

        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(
                new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("当前Java环境不支持RSA", e);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("无效的密钥格式");
    }
}

}

//POST调用时的HTTP方法

public static Map sendBodyPost(String url, Object params) {
	OutputStreamWriter out = null;
	BufferedReader in = null;
	StringBuilder result = new StringBuilder();
	Map map = new HashMap();
	try {
		URL realUrl = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
		String param = JSONObject.toJSONString(params);
		// 发送POST请求必须设置如下两行
		conn.setDoOutput(true);
		conn.setDoInput(true);
		// POST方法
		conn.setRequestMethod("POST");
		// 设置通用的请求属性
		conn.setRequestProperty("accept", "*/*");
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		conn.setRequestProperty("Content-Type", "application/json");
		map = getToken("POST", HttpUrl.parse(url), param);
		conn.setRequestProperty("Authorization", "WECHATPAY2-SHA256-RSA2048" + " " + map.get("sign"));
		conn.connect();
		// 获取URLConnection对象对应的输出流
		out = new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8);
		// 发送请求参数

		logger.info("param:" + param);
		out.write(param);
		// flush输出流的缓冲
		out.flush();
		// 定义BufferedReader输入流来读取URL的响应
		in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
		String line;
		while ((line = in.readLine()) != null) {
			result.append(line);
		}
	} catch (Exception e) {
		e.printStackTrace();
		result.append("error");
	}
	// 使用finally块来关闭输出流、输入流
	finally {
		try {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				in.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
			result.append("error");

		} finally {
			Map maps = new HashMap();
			if (result.toString().contains("error")) {
				maps.put("result", result.toString());
			} else {
				maps.put("result", JSONObject.parseObject(result.toString()));
			}
			maps.put("sign", map.get("sign"));
			maps.put("timestamp", map.get("timestamp"));
			maps.put("noncestr", map.get("noncestr"));
			return maps;
		}
	}

}

//GET方法 他们的区别就是在生成签名时body为空

}

经验分享 程序员 微信小程序 职场和发展