Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the API v3 interface

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "how to use API v3 interface". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Version of jdk:1.8wechatpay-apache-httpclient:0.2.2 application

The author takes WeChat Mini Programs payment interface as an example to explain, as for Mini Program registration, authentication, WeChat Pay registration this article does not explain.

Basic configuration 1. Apply for merchant API certificate

Log in to WeChat Pay backend, enter the account center, and set API security settings, as shown below.

Apply for a merchant certificate, as shown below

After clicking the "apply for Certificate" button, the API certificate application box pops up, such as the following figure downloads the certificate tool according to the prompts. Do not close the current page, but open it after downloading the certificate tool, as shown below.

After clicking the "apply for Certificate" button, enter the interface to fill in the merchant information. After testing, the merchant information is automatically filled in. Click "next" in the following picture to enter the copy request string interface. If you copy the certificate request string in the following picture, go back to the above WeChat Pay background application API certificate page, copy the request string, and automatically help you copy and paste after testing. Click "next" after copying the request string to enter the step of copying the certificate string. Click "copy Certificate string" in the following figure, and paste the copied certificate string into the certificate tool. Click "next" to complete the merchant certificate application. If the merchant API certificate has been generated, click View Certificate folder to view the certificate information. The following figure shows that the serial number and validity period of the merchant API certificate can be obtained at the merchant backend of WeChat Pay, as shown below.

two。 Set the interface key

To set the API key, at this stage, because all the old interfaces of WeChat Pay have not been upgraded to API v3, which involves the coexistence of new and old interfaces, both API key and APIV3 key need to be set. For new and old interfaces, please refer to WeChat Pay's development document, API v2, old version key setting, API v3 key setting.

3. Download platform certificate

Wechat platform certificate download, check the development documents, Wechat has provided a certificate download tool as follows

Follow the Wechat official account at the end of this article and reply to "666" to get common development kits, including commonly used development components and Wechat certificate download tools to save download time.

Download the platform certificate to local and execute the command

The required parameters are: merchant's private key file, namely-f (path of apiclient_key.pem file in merchant's API certificate) certificate decryption key, namely-k (APIv3 key set by WeChat Pay backstage) merchant number, namely-m (WeChat Pay merchant number, which can be checked in WeChat Pay backstage) the path where the certificate is saved, that is, the serial number of the merchant certificate (Wechat platform certificate storage path) That is, the optional parameters of-s (merchant API certificate, that is, the serial number of the merchant API certificate applied for in the first step above) are: WeChat Pay certificate, which is used for signature verification, that is, the complete command-c is as follows: java-jar CertificateDownloader-1.1.jar-k ${apiV3key}-m ${mchId}-f ${mchPrivateKeyFilePath}-s ${mchSerialNo}-o ${outputFilePath}

At this point, the basic configuration parameters are ready

Interface measurement

Understand some parameter concepts in the interface before requesting the interface. The merchant API certificate and the platform certificate are the most easily confused in the first contact, as shown in the following figure.

WeChat Pay API official client

In the past, WeChat Pay always complained that the interface documents were not friendly and there was no sdk, but now API v3 provides you with a client, which can be liked. For developers, the demo code can be directly brought over and the configuration parameters can be changed. It is simply a great concern for programmers, and Ali is relatively good at this.

Talk is cheap, show me the code

1. Client

In the form of a post request, a get request is similar

Private static String basePostRequest (String requestUrl,String requestJson) {CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; HttpEntity entity = null; try {PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey (new ByteArrayInputStream (privateKey.getBytes ("utf-8"); X509Certificate wechatpayCertificate = PemUtil.loadCertificate (new ByteArrayInputStream (certificate.getBytes ("utf-8"); ArrayList listCertificates = new ArrayList (); listCertificates.add (wechatpayCertificate) HttpClient = WechatPayHttpClientBuilder.create () .withMerchant (mchId, mchSerialNo, merchantPrivateKey). WithWechatpay (listCertificates) .build (); HttpPost httpPost = new HttpPost (requestUrl); / / NOTE: charset=utf-8 is recommended. HttpCore versions earlier than 4.4.6 can not set the character set correctly, which may result in signature error StringEntity reqEntity = new StringEntity (requestJson, ContentType.create ("application/json", "utf-8"); httpPost.setEntity (reqEntity); httpPost.addHeader ("Accept", "application/json"); response = httpClient.execute (httpPost); entity = response.getEntity () Return EntityUtils.toString (entity);} catch (Exception e) {e.printStackTrace ();} finally {/ / close stream} return null;}

Parameter description is involved in the method

Class PemUtil.java is com.wechat.pay.contrib.apache.httpclient.util.PemUtil

Request signature and response signature verification the client has handled it for you, and I have a little affection for WeChat Pay's development document. The joint debugging test of the interface can be completed by passing in the interface address and the corresponding interface parameter JSON data according to the specific interface method.

two。 Signature of payment and adjustment parameters

Take Mini Program to adjust the payment interface as an example to briefly explain the parameter signature method. First, take a look at what the signature says in the document, as shown in the following figure.

/ * WeChat Pay-frontend call payment parameter * prepay_id=wx201410272009395522657a690389285100 * @ param packageStr pre-order API returns data pre-payment transaction session ID prepay_id * @ return * / public static Map createPayParams (String packageStr) {Map resultMap = new HashMap (); String nonceStr = StringUtil.getUUID (); Long timestamp = System.currentTimeMillis () / 1000 String message = buildMessage (timestamp, nonceStr, packageStr); String signature = null; try {signature = sign (message.getBytes ("utf-8"));} catch (UnsupportedEncodingException e) {e.printStackTrace ();} resultMap.put ("appId", appId); resultMap.put ("timeStamp", timestamp.toString ()); resultMap.put ("nonceStr", nonceStr) ResultMap.put ("package", packageStr); resultMap.put ("signType", "RSA"); resultMap.put ("paySign", signature); return resultMap } Universe * * WeChat Pay-frontend evokes payment parameters-signature * @ param message signature data * @ return * / public static String sign (byte [] message) {try {Signature sign = Signature.getInstance ("SHA256withRSA"); sign.initSign (getPrivateKey (keyFilePath)); sign.update (message) Return Base64.getEncoder () .encodeToString (sign.sign ());} catch (Exception e) {e.printStackTrace ();} return null } return appId * * WeChat Pay-frontend call payment parameter-build signature parameter * @ param nonceStr signature data * @ return * / public static String buildMessage (long timestamp, String nonceStr, String packageStr) {return appId + "\ n" + timestamp + "\ n" + nonceStr + "\ n" + packageStr + "\ n" * WeChat Pay-payment parameter evoked by frontend-get merchant private key * * @ param filename private key file path (required) * @ return private key object * / 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 ("current Java environment does not support RSA", e);} catch (InvalidKeySpecException e) {throw new RuntimeException ("invalid key format");}}

Parameter description is involved in the method

3. Callback notification

Callback notification involves signature verification and decryption

Callback data acquisition

String body = request.getReader () .lines () .collect (Collectors.joining ())

Check the signature

/ * * callback check tag * https://pay.weixin.qq.com/wiki/doc/apiv3/wechatpay/wechatpay4_1.shtml * @ param wechatpaySerial callback head header * @ param wechatpaySignature callback head header * @ param wechatpayTimestamp callback head header * @ param wechatpayNonce callback head header * @ param body request data * @ return * / public static boolean responseSignVerify (String wechatpaySerial, String wechatpaySignature, String wechatpayTimestamp String wechatpayNonce, String body) {FileInputStream fileInputStream = null Try {String signatureStr = buildMessage (wechatpayTimestamp, wechatpayNonce, body); Signature signer = Signature.getInstance ("SHA256withRSA"); fileInputStream = new FileInputStream (weixin_platform_cert_path); X509Certificate receivedCertificate = loadCertificate (fileInputStream); signer.initVerify (receivedCertificate); signer.update (signatureStr.getBytes (StandardCharsets.UTF_8)) Return signer.verify (Base64.getDecoder (). Decode (wechatpaySignature));} catch (Exception e) {e.printStackTrace ();} finally {if (fileInputStream! = null) {try {fileInputStream.close ();} catch (IOException e) {e.printStackTrace () } return false;} / * callback verification-load Wechat platform certificate * @ param inputStream * @ return * / public static X509Certificate loadCertificate (InputStream inputStream) {try {CertificateFactory cf = CertificateFactory.getInstance ("X509"); X509Certificate cert = (X509Certificate) cf.generateCertificate (inputStream) Cert.checkValidity (); return cert;} catch (CertificateExpiredException e) {throw new RuntimeException ("Certificate expired", e);} catch (CertificateNotYetValidException e) {throw new RuntimeException ("Certificate not valid", e);} catch (CertificateException e) {throw new RuntimeException ("invalid Certificate", e) }} / * callback check-build signature data * @ param * @ return * / public static String buildMessage (String wechatpayTimestamp, String wechatpayNonce, String body) {return wechatpayTimestamp + "\ n" + wechatpayNonce + "\ n" + body + "\ n";}

Parameter description is involved in the method

Decryption

/ / https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_5.shtmlAesUtil wxAesUtil = new AesUtil (apiv3.getBytes ()); String jsonStr = wxAesUtil.decryptToString ("associated_data" .getBytes (), "nonce" .getBytes (), "ciphertext")

Parameter description is involved in the method

This is the end of "how to use the API v3 interface". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report