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 + "\n"
+ canonicalUrl + "\n"
+ timestamp + "\n"
+ nonceStr + "\n"
+ body + "\n");
return method + "\n"
+ canonicalUrl + "\n"
+ timestamp + "\n"
+ nonceStr + "\n"
+ body + "\n";
}
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为空
public static String doGet(String url, Map<String, String> params,String param) {
// 返回结果
String result = "";
// 创建HttpClient对象
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = null;
try {
// 拼接参数,可以用URIBuilder,也可以直接拼接在?传值,拼在url后面,如下--httpGet = new
// HttpGet(uri+"?id=123");
URIBuilder uriBuilder = new URIBuilder(url);
if (null != params && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
uriBuilder.addParameter(entry.getKey(), entry.getValue());
// 或者用
// 顺便说一下不同(setParameter会覆盖同名参数的值,addParameter则不会)
// uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
URI uri = uriBuilder.build();
// 创建get请求
httpGet = new HttpGet(uri);
httpGet.setHeader("accept", "*/*");
httpGet.setHeader("connection", "Keep-Alive");
httpGet.setHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
httpGet.setHeader("Authorization","WECHATPAY2-SHA256-RSA2048"+" "+getToken("GET", HttpUrl.parse("https://api.mch.weixin.qq.com/v3/payscore/serviceorder?"+param),"").get("sign"));
HttpResponse response = httpClient.execute(httpGet);
Header[] s=httpGet.getHeaders("Authorization");
System.err.println(String.valueOf(s[0]));
result = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
ExceptionUtils.getStackTrace(e);
result="error";
return result;
} finally {
// 释放连接
if (null != httpGet) {
httpGet.releaseConnection();
}
}
return result;
}
}
/**
* 创建一个支付分订单
*
* @param wechatNumParam
* @return
*/
public static Map<String, Object> PayMent(WechatNumParam wechatNumParam) {
TimeRange timeRange = new TimeRange();
timeRange.setStart_time(BasicInfo.serverStartTime);
wechatNumParam.setTime_range(timeRange);
return HttpRequestWechatNumUtils.sendBodyPost("https://api.mch.weixin.qq.com/v3/payscore/serviceorder", object2Map(wechatNumParam));
}
/**
* 查询支付分订单
*
* @param wechatNumParam
* @return
*/
public static String queryPay(WechatNumParam wechatNumParam) {
StringBuffer string = new StringBuffer();
string.append("service_id=" + BasicInfo.XIAO_SERVICEID);
string.append("&appid=" + BasicInfo.XIAO_AppID);
string.append("&out_order_no=" + wechatNumParam.getOut_order_no());
Map<String, String> map = new HashMap<String, String>();
map.put("service_id", BasicInfo.XIAO_SERVICEID);
map.put("appid", BasicInfo.XIAO_AppID);
map.put("out_order_no", wechatNumParam.getOut_order_no());
return doGet("https://api.mch.weixin.qq.com/v3/payscore/serviceorder", map, string.toString());
}
由于微信支付分刚推出没多久,网上案例实在少,本人亲自踩坑,现已项目上线,如有问题可互相讨教,谢谢