微信支付v3接口(jsapi,小程序,app)调起支付签名java示例代码
替换参数即可使用
注意:需要按照对应的支付文档填写完整的prepay_id的,例如:
构建签名代码:
package com.wxpay.demo;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Base64;
public class CreateSign02 {
String getToken(String appid,String prepay_id) throws IOException, SignatureException, NoSuchAlgorithmException, InvalidKeyException {
//随机字符串
String nonceStr = "asdasdffafafgddfvc";//真!随机字符串
//时间戳
long timestamp = System.currentTimeMillis() / 1000;
//从下往上依次生成
String message = buildMessage(appid, timestamp, nonceStr, prepay_id);
//签名
String signature = sign(message.getBytes("utf-8"));
return signature ;
}
String sign(byte[] message) throws NoSuchAlgorithmException, SignatureException, IOException, InvalidKeyException {
//签名方式
Signature sign = Signature.getInstance("SHA256withRSA");
//私钥,通过MyPrivateKey来获取,这是个静态类可以接调用方法 ,需要的是_key.pem文件的绝对路径配上文件名
sign.initSign(MyPrivatekey.getPrivateKey("E:\\miyao\\apiclient_key.pem"));
sign.update(message);
return Base64.getEncoder().encodeToString(sign.sign());
}
/**
* 按照前端签名文档规范进行排序,\n是换行
* @param appid
* @param timestamp
* @param nonceStr
* @param prepay_id
* @return
*/
String buildMessage(String appid, long timestamp,String nonceStr,String prepay_id) {
return appid + "\n"
+ timestamp + "\n"
+ nonceStr + "\n"
+ prepay_id + "\n";
}
}
代码加载商户api证书私钥代码(用于上面的签名生成):
package com.wxpay.demo;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
public class MyPrivatekey {
/**
* 获取私钥。
*
* @param filename 私钥文件路径 (required)
* @return 私钥对象
*/
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.getMimeDecoder().decode(privateKey)));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("当前Java环境不支持RSA", e);
} catch (InvalidKeySpecException e) {
throw new RuntimeException("无效的密钥格式");
}
}
}
我就是上面这个细节没注意,APP支付是这个WX1217752501201407033233368018,
jsapi支付就是这个 prepay_id=wx201410272009395522657a690389285100
可以发一份python flask生成签名的代码嘛,实在不会,呜呜呜呜