Home > Java > javaTutorial > body text

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

零下一度
Release: 2017-07-19 13:26:20
Original
3871 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!