search
HomeJavajavaTutorialDetailed explanation of WeChat public account payment development (java) examples

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>
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> backxml = new HashMap<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> 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></return_code>"+ "<return_msg></return_msg>" + "</xml> ";//业务处理开始                   //业务处理结束                }
                BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());out.write(resXml.getBytes());out.flush();out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }return resXml;
    }</string></string></string>
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
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
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor