国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1、 前言
2. Detailed explanation of WeChat payment in Java (1): API V3 version signature
Parsing the API certificate
3. V3 signature
Signature format
After the signature is generated, it will be combined with some parameters to form a
Home Java JavaBase Detailed explanation of WeChat payment in Java (1): API V3 version signature

Detailed explanation of WeChat payment in Java (1): API V3 version signature

Oct 27, 2020 pm 05:20 PM
java WeChat Pay

java基礎(chǔ)教程欄目介紹Java中的微信支付,實(shí)現(xiàn)API V3版本簽名。

Detailed explanation of WeChat payment in Java (1): API V3 version signature

1、 前言

最近在折騰微信支付,證書還是比較煩人的,所以有必要分享一些經(jīng)驗(yàn),減少你在開發(fā)微信支付時(shí)的踩坑。目前微信支付的API已經(jīng)發(fā)展到V3版本,采用了流行的Restful風(fēng)格。

Detailed explanation of WeChat payment in Java (1): API V3 version signature

今天來分享微信支付的難點(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)行簽名。通過商戶平臺(tái)你可以設(shè)置并獲取Detailed explanation of WeChat payment in Java (1): API V3 version signature。

Detailed explanation of WeChat payment in Java (1): API V3 version signature

切記在第一次設(shè)置的時(shí)候會(huì)提示下載,后面就不再提供下載了,具體參考說明。

Detailed explanation of WeChat payment in Java (1): API V3 version signature說明

設(shè)置后找到zip壓縮包解壓,里面有很多文件,對(duì)于JAVA開發(fā)來說只需要關(guān)注apiclient_cert.p12這個(gè)證書文件就行了,它包含了公私鑰,我們需要把它放在服務(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();????????????//?證書的序列號(hào)?也有用
????????????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 certificate apiclient_cert.p12 classpath path, generally we will put it under the resources 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 to Tenpay Certificate.
  • keyPass Certificate password, this default is the merchant number, it also needs to be used in other configurations is mchid, 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請(qǐng)求方法\n
URL\n
請(qǐng)求時(shí)間戳\n
請(qǐng)求隨機(jī)串\n
請(qǐng)求報(bào)文主體\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 ##POST or PUT, please use to actually send the JSON message of . For image upload API, please use the JSON message corresponding to meta.
Generate signature

Then we use the merchant’s private key to perform SHA256 with RSA signature on the

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???????請(qǐng)求方法??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)前時(shí)間戳???因?yàn)橐渲玫絋OKEN?中所以?簽名中的要跟TOKEN?保持一致
?*?@param?nonceStr?????隨機(jī)字符串??要和TOKEN中的保持一致
?*?@param?body?????????請(qǐng)求體?GET?為?""?POST?為JSON
?*?@param?keyPair??????商戶API?證書解析的密鑰對(duì)??實(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:

The merchant who initiated the request (including directly connected merchants , service provider or channel provider) merchant number
    mchid
  • Merchant API certificate serial number
  • serial_no
  • , used to declare the certificate used

    Request random string
  • nonce_str
  • ##Timestamp

    timestamp
  • Signature value

    signature
  • Token
  • Generated core code:
/**
?*?生成Token.
?*
?*?@param?mchId?商戶號(hào)
?*?@param?nonceStr???隨機(jī)字符串?
?*?@param?timestamp??時(shí)間戳
?*?@param?serialNo???證書序列號(hào)
?*?@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.

Related free learning recommendations:

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

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

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

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.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

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

JD Stablecoin Official Website Where to buy JD Stablecoin JD Stablecoin Official Website Where to buy JD Stablecoin Aug 01, 2025 pm 06:51 PM

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.

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

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

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

Google Chrome cannot open local files Google Chrome cannot open local files Aug 01, 2025 am 05:24 AM

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Understanding Network Ports and Firewalls Understanding Network Ports and Firewalls Aug 01, 2025 am 06:40 AM

Networkportsandfirewallsworktogethertoenablecommunicationwhileensuringsecurity.1.Networkportsarevirtualendpointsnumbered0–65535,withwell-knownportslike80(HTTP),443(HTTPS),22(SSH),and25(SMTP)identifyingspecificservices.2.PortsoperateoverTCP(reliable,c

See all articles