In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "How to understand API V3 version signature of Weixin Pay in Java". The explanation content in this article is simple and clear, and easy to learn and understand. Please follow the idea of Xiaobian to study and learn "How to understand API V3 version signature of Weixin Pay in Java" together!
1. preface
Recently, Weixin Pay has been tossing around, and certificates are still annoying, so it is necessary to share some experiences and reduce your steps when developing Weixin Pay. At present, the API of Weixin Pay has been developed to V3 version, adopting the popular Restful style.
Difference between Weixin Pay V2 and V3
2. API certificate
In order to ensure the security of fund sensitive data, we ensure that the fund transactions in our business are foolproof. At present, Weixin Pay is signed by the private key provided in the authoritative CA certificate (API certificate) issued by the third party. Through the merchant platform you can set up and obtain API certificates.
API certificate
Remember that when you set it for the first time, you will be prompted to download it. Later, you will no longer be able to download it. Please refer to the instructions for details.
API Certificate Description
After setting up, find the zip compression package decompression, there are many files, for JAVA development only need to pay attention to apiclient_cert.p12 this certificate file on the line, it contains the public and private keys, we need to put it on the server and use Java Parse.p12 file to obtain the public key and private key.
Be sure to ensure that the certificate is secure on the server side, which involves financial security.
Parse API certificate
Next is the resolution of the certificate, certificate resolution has many methods on the Internet, here I use a more "formal" method to resolve, using JDK security package java.security.KeyStore to resolve.
Weixin Pay API certificate uses PKCS12 algorithm. We obtain the carrier KeyPair of public and private key pairs and certificate serial number serialNumber through KeyStore. I encapsulate the tool class (serial number you handle by yourself):
import org.springframework.core.io.ClassPathResource; import java.security.KeyPair; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; /** * KeyPairFactory * * @author dax * @since 13:41 **/ public class KeyPairFactory { private KeyStore store; private final Object lock = new Object(); /** * Acquire public and private keys. * * @param keyPath the key path * @param keyAlias the key alias * @param keyPass password * @return the key pair */ public KeyPair createPKCS12(String keyPath, String keyAlias, String keyPass) { ClassPathResource resource = new ClassPathResource(keyPath); char[] pem = keyPass.toCharArray(); try { synchronized (lock) { if (store == null) { synchronized (lock) { store = KeyStore.getInstance("PKCS12"); store.load(resource.getInputStream(), pem); } } } X509Certificate certificate = (X509Certificate) store.getCertificate(keyAlias); certificate.checkValidity(); //Serial number of certificate is also useful String serialNumber = certificate.getSerialNumber().toString(16).toUpperCase(); //Public key of certificate PublicKey publicKey = certificate.getPublicKey(); //certificate's private key PrivateKey storeKey = (PrivateKey) store.getKey(keyAlias, pem); return new KeyPair(publicKey, storeKey); } catch (Exception e) { throw new IllegalStateException("Cannot load keys from store: " + resource, e); } } }
Familiar can be seen is fat brother Spring Security tutorial JWT with a modified version of the public and private key extraction method, you can compare the differences.
There are three parameters in this method, which must be explained here:
keyPath API certificate apiclient_cert.p12 classpath path, generally we will put under the resources path, of course, you can modify the way to obtain the certificate input stream.
keyAlias alias certificate alias, this WeChat document is not, fat brother by loading the certificate DEBUG to obtain the value fixed as Tenpay Certificate.
keyPass certificate password, this default is the merchant number, in other configurations also need to use is mchid, that is, you use super administrator login WeChat merchant platform in the personal data of a string of numbers.
3. V3 Signature
The signature of Weixin Pay V3 version is that when we call the specific API of Weixin Pay, we carry a specific code string in the HTTP request header for the Weixin Pay server to verify the source of the request to ensure that the request is authentic.
signature format
The specific format of the signature string, a total of five lines can not be less, each line ends with a newline\n.
HTTP Request Method\n URL\n Request Timestamp\n Request Random String\n Request Message Body\n
HTTP request method The request method required by the Weixin Pay API you call, such as POST for APP payment.
For example, the URL in the APP payment document is https://api.mch.weixin.qq.com/v3/pay/transactions/app, and the URL participating in the signature is obtained by removing the domain name part. If there are query parameters in the request, the URL should be appended with '? 'and the corresponding query string. Here is/v3/pay/transactions/app.
Request the timestamp server system timestamp, ensure that the server time is correct and use System.currentTimeMillis() / 1000 to get it.
Request random string Find a tool class to generate a string similar to 593BEC0C930BF1AFEB40B4A08C8FB242 on the line.
If the request message body is GET request, the empty character "" is directly used; when the request method is POST or PUT, please use the JSON message actually sent. For image upload API, please use JSON message corresponding to meta.
generate a signature
Then we use the merchant private key to SHA256 with RSA signature the string to be signed according to the above format, and Base64 encode the signature result to obtain the signature value. The core Java code is:
/** * V3 SHA256 with RSA signature. * * @param method Request method GET POST PUT Deleted etc. * @param canonicalUrl e.g. https://api.mch.weixin.qq.com/v3/pay/transactions/app? version=1 --> /v3/pay/transactions/app? version=1 * @param timestamp current timestamp Because it needs to be configured in TOKEN, the signature should be consistent with TOKEN * @param nonceStr Random string to match TOKEN * @param body GET is " POST is JSON * @param keyPair The private key * @return the string */ @SneakyThrows String sign(String method, String canonicalUrl, long timestamp, String nonceStr, String body, KeyPair keyPair) { String signatureStr = Stream.of(method, canonicalUrl, String.valueOf(timestamp), nonceStr, body) .collect(Collectors.joining("\n", "", "\n")); Signature sign = Signature.getInstance("SHA256withRSA"); sign.initSign(keyPair.getPrivate()); sign.update(signatureStr.getBytes(StandardCharsets.UTF_8)); return Base64Utils.encodeToString(sign.sign()); }
4. using a signature
After the signature is generated, it will form a Token together with some parameters and place it in the Authorization request header of the corresponding HTTP request. The format is:
Authorization: WECHATPAY2-SHA256-RSA2048 {Token}
Token consists of the following five parts:
Merchant number mchid of the requesting merchant (including direct merchant, service provider or channel provider)
Merchant API certificate serial number serial_no, used to declare the certificate used
Request random string nonce_str
Time stamp
signature value signature
Token generation core code:
/** * Generate Token. * * @param mchId Merchant #* @param nonceStr Random string * @param timestamp timestamp * @param serialNo Certificate Serial Number * @param signature Signature * @return the string */ String token(String mchId, String nonceStr, long timestamp, String serialNo, String signature) { final String TOKEN_PATTERN = "mchid=\"%s\",nonce_str=\"%s\",timestamp=\"%d\",serial_no=\"%s\",signature=\"%s\""; //generate token return String.format(TOKEN_PATTERN, wechatPayProperties.getMchId(), nonceStr, timestamp, serialNo, signature); }
The signature can be used by placing the Token generated in the request header according to the above format.
Thank you for reading. The above is the content of "How to understand API V3 version signature of Weixin Pay in Java." After studying this article, I believe you have a deeper understanding of how to understand API V3 version signature of Weixin Pay in Java. The specific use situation needs to be verified by practice. Here is, Xiaobian will push more articles related to knowledge points for everyone, welcome to pay attention!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.