Home Java javaTutorial Detailed explanation of WeChat public account payment development (java) examples

Detailed explanation of WeChat public account payment development (java) examples

Jul 19, 2017 pm 01:26 PM
java develop pay

In the past, payment in the company's project development was done using Alibaba's payment, which was called simple and casual; sadly, now the company has developed a WeChat official account, so I stepped into the WeChat payment development that is full of pitfalls. . .

Business process:

This WeChat official website explains it in great detail (portal:).

 

The general process is: the user clicks a payment button-->Backend processing (actually, it encapsulates the necessary data for payment and obtains prepay_id, and then combines it with Some necessary parameters are encapsulated and passed to the front desk)-->The front desk receives the data and calls WeChat's js to process the data and call payment-->The user sees an interface for entering a password, including the amount and other information--> After the user enters the password, a successful payment page will appear. At the same time, WeChat will call back our interface to notify us of the payment result (this part of the process is completed by WeChat itself, we don’t need to worry about it) --> Return to the system itself page.

Development Steps:

1. Set up the payment directory

This official document is very disgusting. I was confused and a little dizzy after reading it. Although I can’t understand it, I think it looks awesome! Portal:

2. Set the authorized domain name

These 2 steps Once you're done, you can take a break because the big pit is coming. . .

3. The merchant server calls the unified ordering interface to request an order

What does this do? When I first started doing it, I was confused, but who calls the WeChat payment team nb? How can they show their sophistication without adding some things that you don’t understand? . . If you don’t understand, just follow the document.

Portal:, WeChat official gave a detailed explanation of the parameters. After looking at it for a long time, I summarized it by encapsulating some necessary parameters and then accessing this interface to obtain data. The following are several commonly used parameters. Directly copy other people’s introduction in detail:

appid ==Application ID==Log in to the WeChat public account backend-development-basic configuration
mch_id == WeChat payment Merchant ID == Log in to the WeChat payment backend and you will see
device_info== Device number == Terminal device number (store number or cashier device ID). Note: Please pass " WEB"
body==Product description==Brief description of the product or payment order (it is recommended to send it in English at the beginning, try not to send it in Chinese first, otherwise there will be no way to check if there is a problem with the signature later)
trade_type==Transaction type==Values ​​are as follows: JSAPI, NATIVE, APP. The JSAPI we use here. As the title already said, it is WeChat official account payment. For their differences, please refer to
ps: JSAPI--public account payment, NATIVE--native scan code payment, APP--app payment, the parameters of the unified order interface trade_type can be found here. MICROPAY--Swipe card payment. Card payment has a separate payment interface and does not call the unified order interface
nonce_str==random string==random string, no longer than 32 bits (reference algorithm)
notify_url==Notification address==Receive the WeChat payment asynchronous notification callback address. The notification URL must be a directly accessible URL and cannot carry parameters. (Here, what’s a good name? Just name it casually, it won’t be used for a while anyway)
out_trade_no==Merchant order number==Order number within the merchant system, within 32 characters, can be Contains letters (reference:) (Every time I read the official explanation on WeChat, I get more confused. Is there any? It doesn’t matter, I will just send 1.)
total_fee==Total amount= =Total amount of the order, The unit is cents (note this, I didn’t pay attention at first, what was passed was 0.01, and development costs 1 cent, and then it became a tragedy. After reading it many times, I found out that the unit is cents. )
openid==User ID==trade_type=JSAPI, this parameter must be passed, the user’s unique identification under the merchant’s appid. (If you don’t know where this comes from, it doesn’t matter. Didn’t WeChat write a document for us?)
And the most important one, important characters always appear at the end.
attach==Additional data, returned as is in query API and payment notification, can be used as custom parameters. (I think this is quite useful and can be used to store business data, because I process business data in WeChat callbacks. Using this parameter is safe and painless)
sign==Signature==Official signature algorithm. . I don’t understand it, I don’t quite understand it. If you think you understand it, it doesn’t matter. If you don’t encounter a few signature errors, are you embarrassed to say that you have done WeChat payment development? (I personally recommend using the tools in the official SDK when developing, which can save money. It’s a lot of trouble to download the SDK and calling examples corresponding to the Java API here. There are many tools in it)
said that this sign has a more important parameter. Parameters involved in the signature. Anyway, it took me a long time to find it. (The company operation applied for WeChat payment. When I asked her for it, his expression looked like this.)
key==key setting path: WeChat merchant platform (pay.weixin.qq.com) -->Account settings-->API security-->Key settings (this is very important, it is used for signatures)

##The summary of this part is, first encapsulate the data into a map and then convert it into xml through a tool (the tool is mentioned above, go back and read it yourself), and then request [WeChat Unified Order Interface] through post request. If there is no problem with sign, it will Return an xml with a lot of data in it. What we want is prepay_id, which is this parameter. Then the signature is generated and returned to the front desk. OK, this step is completed.

Problem summary (problems I encountered during this process): 1 (Important) appid and openid must match, in other words, the user's openid must be under the current official account Users (we have several public accounts, you may not encounter this problem, but it is very important, let me talk about it first) 2

<span style="text-decoration: underline; color: #ff0000">第二步,生成签名并返回到前台</span><span style="color: #ff0000">这个过程中一定要注意参数一定要写对了,大小写,是否有空格,我在这上面掉了一个大坑,界面调用支付时一直闪退,注意.<br><br></span>
Copy after login
4. H5 activates WeChat payment The built-in JS

The parameters returned from the background to the front desk should include the following items:
appId==This is unchanged==It will never change
timeStamp==Timestamp==Rule:. After reading it, I still look confused. It doesn’t matter, we have the tool class.

nonceStr == Anyway, I used the same random string as the signature just now. In theory, it shouldn't matter if you don't use it. Diligent friends can try

package==Order details extended string==prepay_id parameter value returned by the unified order interface, the submission format is such as: prepay_id=** *(You guessed it right. The prepay_id we just spent so much effort to obtain is used here)
signType==Signature method==Signature algorithm, temporarily supports MD5
paySign ==Signature== This signature needs to be regenerated in the background. Use the above 4 parameters + a key (never change). (The timestamp when I generated the signature and the timestamp sent back to the front desk are the same timeStamp. Does it work if they are different? There is no verification)
Code to generate paySign
Note: When generating prepay_id, the appid is a lowercase i. When generating paySign, the appId is an uppercase I. The two are different.
If If everything goes well, this page will appear
After all these are done, you can relax
##5 , WeChat callback processing
This part has the following 3 small steps

1) Parse the passed flow information and verify the information contained in the flow by re-signing Correctness. It is to determine whether this information is sent by WeChat

  2) If return_code and result_code are both SUCCESS, handle the merchant's own business logic. It’s just the payment status of the order and some other information.

3) Tell WeChat that I have received your return value. No need to post again.

Without further ado, let’s just post the code!

public String return_data(HttpServletRequest request, HttpServletResponse response) throws Exception {
        logger.info("微信支付请求回调了");
        String resXml = "";
        Map<String, String> backxml = new HashMap<String, String>();
        InputStream inStream;try {
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();byte[] buffer = new byte[1024];int len = 0;while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息Map<String, String> map = WXPayUtil.xmlToMap(result);if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {if (WXPayUtil.isSignatureValid(map, PayConfigUtil.API_KEY)) {
                    logger.info("微信支付-签名验证成功");//                    backxml.put("return_code", "SUCCESS");//                    backxml.put("return_msg", "OK");//                    String toXml = WXPayUtil.mapToXml(backxml);//                    response.getWriter().write(toXml);resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";//业务处理开始                   //业务处理结束                }
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());out.write(resXml.getBytes());out.flush();out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }return resXml;
    }
Copy after login
Remember,
3. Do the merchant server call the unified ordering interface to request an order

##attach parameter? It is very convenient to bring business data here

#

The above is the detailed content of Detailed explanation of WeChat public account payment development (java) examples. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles