Detailed explanation of WeChat payment in Java (1): API V3 version signature
Oct 27, 2020 pm 05:20 PMjava基礎(chǔ)教程欄目介紹Java中的微信支付,實(shí)現(xiàn)API V3版本簽名。
1、 前言
最近在折騰微信支付,證書還是比較煩人的,所以有必要分享一些經(jīng)驗(yàn),減少你在開發(fā)微信支付時的踩坑。目前微信支付的API已經(jīng)發(fā)展到V3版本,采用了流行的Restful風(fēng)格。
今天來分享微信支付的難點(diǎn)——簽名,雖然有很多好用的SDK但是如果你想深入了解微信支付還是需要了解一下的。
2. Detailed explanation of WeChat payment in Java (1): API V3 version signature
為了保證資金敏感數(shù)據(jù)的安全性,確保我們業(yè)務(wù)中的資金往來交易萬無一失。目前微信支付第三方簽發(fā)的權(quán)威的CA證書(Detailed explanation of WeChat payment in Java (1): API V3 version signature)中提供的私鑰來進(jìn)行簽名。通過商戶平臺你可以設(shè)置并獲取Detailed explanation of WeChat payment in Java (1): API V3 version signature。
切記在第一次設(shè)置的時候會提示下載,后面就不再提供下載了,具體參考說明。
設(shè)置后找到zip
壓縮包解壓,里面有很多文件,對于JAVA開發(fā)來說只需要關(guān)注apiclient_cert.p12
這個證書文件就行了,它包含了公私鑰
,我們需要把它放在服務(wù)端并利用Java解析.p12
文件獲取公鑰私鑰。
務(wù)必保證證書在服務(wù)器端的安全,它涉及到資金安全。
Parsing the API certificate
The next step is to parse the certificate. There are many ways to parse the certificate on the Internet. Here I use a more "formal" method to parse, using the JDK security packagejava.security.KeyStore
to resolve.
The WeChat payment API certificate uses the PKCS12
algorithm. We use KeyStore
to obtain the carrier of the public and private key pair KeyPair
and the certificate serial numberserialNumber
, I encapsulated the tool class:
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();????/** ?????*?獲取公私鑰. ?????* ?????*?@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();????????????//?證書的序列號?也有用 ????????????String?serialNumber?=?certificate.getSerialNumber().toString(16).toUpperCase();????????????//?證書的?公鑰 ????????????PublicKey?publicKey?=?certificate.getPublicKey();????????????//?證書的私鑰 ????????????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); ????????} ????} }復(fù)制代碼
If it looks familiar, you can see that it is a modified version of the public and private key extraction method used by JWT in the Spring Security tutorial of Fat Brother. You can compare the differences. place.
There are three parameters in this method, which must be explained here:
-
keyPath
API certificateapiclient_cert.p12
classpath
path, generally we will put it under theresources
path. Of course, you can modify the way to obtain the certificate input stream. -
keyAlias
The alias of the certificate is not available in this WeChat document. Brother Fat obtained it by DEBUG when loading the certificate and found that the value is fixed toTenpay Certificate
. -
keyPass
Certificate password, this default is the merchant number, it also needs to be used in other configurations ismchid
, that is, you use Super Administrator A string of numbers in the personal profile when logging into the WeChat merchant platform.
3. V3 signature
The signature of WeChat Pay V3 version is that we carry a specific signature in the HTTP request header when we call the specific WeChat Pay API. The encoding string is used by the WeChat payment server to verify the source of the request to ensure that the request is authentic and trustworthy.
Signature format
The specific format of the signature string, no less than five lines in total, each line ends with a newline character \n
.
HTTP請求方法\n URL\n 請求時間戳\n 請求隨機(jī)串\n 請求報文主體\n復(fù)制代碼
-
HTTP request method The request method required by the WeChat payment API you call, for example, APP payment is
POST
. -
URL For example, the APP payment document is
https://api.mch.weixin.qq.com/v3/pay/transactions/app
, except the domain name part Get the URL participating in the signature. If there are query parameters in the request, '?' and the corresponding query string should be appended to the end of the URL. Here is/v3/pay/transactions/app
. -
Request timestamp Server system timestamp, make sure the server time is correct and use
System.currentTimeMillis() / 1000
to obtain it. -
Request a random string Just find a tool to generate a string similar to
593BEC0C930BF1AFEB40B4A08C8FB242
. -
Request message body If it is GET the request is directly null character
""
; when the request method is# When ##POSTor
PUT, please use
to actually send the JSON message of. For image upload API, please use the
JSONmessage corresponding to
meta.
string to be signed in the above format, and ## the signature result #Base64 encodingGet the signature value. The corresponding core Java code is: /**
?*?V3??SHA256withRSA?簽名.
?*
?*?@param?method???????請求方法??GET??POST?PUT?DELETE?等
?*?@param?canonicalUrl?例如??https://api.mch.weixin.qq.com/v3/pay/transactions/app?version=1?——>?/v3/pay/transactions/app?version=1
?*?@param?timestamp????當(dāng)前時間戳???因?yàn)橐渲玫絋OKEN?中所以?簽名中的要跟TOKEN?保持一致
?*?@param?nonceStr?????隨機(jī)字符串??要和TOKEN中的保持一致
?*?@param?body?????????請求體?GET?為?""?POST?為JSON
?*?@param?keyPair??????商戶API?證書解析的密鑰對??實(shí)際使用的是其中的私鑰
?*?@return?the?string
?*/@SneakyThrowsString?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());
}復(fù)制代碼
4. Use the signature
After the signature is generated, it will be combined with some parameters to form a
Token and place it in the Authorization# corresponding to the HTTP request. ##In the request header, the format is:
Authorization:?WECHATPAY2-SHA256-RSA2048?{Token}復(fù)制代碼
Token consists of the following five parts: - mchid
-
Merchant API certificate serial number serial_no - , used to declare the certificate used
Request random string nonce_str -
timestamp##Timestamp
-
signatureSignature value
-
Token Generated core code:
/** ?*?生成Token. ?* ?*?@param?mchId?商戶號 ?*?@param?nonceStr???隨機(jī)字符串? ?*?@param?timestamp??時間戳 ?*?@param?serialNo???證書序列號 ?*?@param?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\"";????//?生成token ????return?String.format(TOKEN_PATTERN, ????????????wechatPayProperties.getMchId(), ????????????nonceStr,?timestamp,?serialNo,?signature); }復(fù)制代碼
Will generate Token
is placed in the request header according to the above format to complete the use of the signature.
5. SummaryIn this article we have conducted a complete analysis of the difficult signatures and the use of signatures in the WeChat Pay V3 version, and also explained the analysis of API certificates. I believe it can help you. Solve some specific problems in payment development.
java basic tutorial
Related article introduction: How to implement the mini program payment function
The above is the detailed content of Detailed explanation of WeChat payment in Java (1): API V3 version signature. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Currently, JD.com has not issued any stablecoins, and users can choose the following platforms to purchase mainstream stablecoins: 1. Binance is the platform with the largest transaction volume in the world, supports multiple fiat currency payments, and has strong liquidity; 2. OKX has powerful functions, providing 7x24-hour customer service and multiple payment methods; 3. Huobi has high reputation in the Chinese community and has a complete risk control system; 4. Gate.io has rich currency types, suitable for exploring niche assets after purchasing stablecoins; 5. There are many types of currency listed on KuCoin, which is conducive to discovering early projects; 6. Bitget is characterized by order transactions, with convenient P2P transactions, and is suitable for social trading enthusiasts. The above platforms all provide safe and reliable stablecoin purchase services.

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear
