In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you the "Java development of Wechat Navicat payment example analysis", the content is easy to understand, clear, hope to help you resolve your doubts, the following let the editor lead you to study and learn about "Java development of Wechat Navicat payment sample analysis" this article.
One: preparatory work
1: first go to the Wechat public platform to register an official account and select the service number
2: register a merchant number on Wechat merchant platform for collection
3: configure the APPID of the corresponding official account in the merchant account
4: asynchronous notification of payment result (need to pay attention)
Note: please first take a detailed look at the official documents and develop them step by step. Everything is based on official documents. Wechat Navicat pays for official documents.
5: be sure to use private network traversal software when testing, otherwise an error will be reported during callback
Second: development code
WeChatPayConfig:
Public class WeChatPayConfig {/ / official account APPID private String APPID = ""; / / merchant number KEY private String KEY = ""; / / merchant number ID private String MCHID = ""; / / callback address of Wechat after payment is completed. If the domain name can be accessed by public network, it cannot be 127.0.0.1 and localhost private String NOTIFY_URL = ";;}
WeChatPayServcie:
Public interface WeChatPayServcie {public Map getWxpayUrl / WeChat Pay order public Map getWxpayUrl (Map sourceMap); / order query public String orderQuery (String out_trade_no);} @ Servicepublic class WeChatPayServiceImpl implements WeChatPayServcie {/ * * WeChat Pay request * @ param sourceMap * @ return * / public Map getWxpayUrl (Map sourceMap) {SortedMap signParams = new TreeMap () String nonce_str = UUID.randomUUID (). ToString (). Trim (). ReplaceAll ("-", "); signParams.put (" appid ", PayConfig.APPID); signParams.put (" mch_id ", PayConfig.MCHID); signParams.put (" nonce_str ", sourceMap.get (" nonce_str ")); signParams.put (" product_id ", sourceMap.get (" prod_id ")); signParams.put (" body ", sourceMap.get (" body ")) SignParams.put ("out_trade_no", sourceMap.get ("out_trade_no")); signParams.put ("total_fee", sourceMap.get ("total_fee")); signParams.put ("spbill_create_ip", WxUtil.getIp ()); signParams.put ("notify_url", PayConfig.NOTYFLY_URL); signParams.put ("trade_type", "NATIVE"); String sign = WxUtil.createSign (signParams,PayConfig.KEY) SignParams.put ("sign", sign); String xmlPackage = WxUtil.parseMapXML (signParams); Map resultMap = new HashMap (); try {String result = HttpUtil.post ("https://api.mch.weixin.qq.com/pay/unifiedorder",xmlPackage); resultMap = WxUtil.parseXmlMap (result);} catch (Exception e) {e.printStackTrace ();} String returnCode = (String) resultMap.get (" return_code ") String returnMsg = (String) resultMap.get ("return_msg"); if (returnCode.equalsIgnoreCase ("FAIL")) {throw new RuntimeException (returnMsg);} String result_code = (String) resultMap.get ("result_code"); if (result_code.equalsIgnoreCase ("FAIL")) {throw new RuntimeException (resultMap.get ("err_code_des"));} String code_url = (String) resultMap.get ("code_url") Map map = new HashMap (); map.put ("code_url", code_url); map.put ("out_trade_no", sourceMap.get ("out_trade_no")); return map } * WeChat Pay order query * @ param out_trade_no * @ return * / public String orderQuery (String out_trade_no) {String nonce_str = UUID.randomUUID (). ToString (). Trim (). ReplaceAll ("-", "); SortedMap signParams = new TreeMap (); signParams.put (" appid ", payConfig.getWeChatPorpetties (). GetAppId ()) SignParams.put ("mch_id", payConfig.getWeChatPorpetties (). GetMchId ()); signParams.put ("out_trade_no", out_trade_no); signParams.put ("nonce_str", nonce_str); String sign = WxUtil.createSign (signParams,payConfig.getWeChatPorpetties (). GetApiKey ()); signParams.put ("sign", sign); String xmlPackage = WxUtil.parseMapXML (signParams); Map resultMap = new HashMap () Try {String result = HttpUtil.post ("https://api.mch.weixin.qq.com/pay/orderquery",xmlPackage); resultMap = WxUtil.parseXmlMap (result);} catch (Exception e) {e.printStackTrace (); throw new RuntimeException (" Channel Network exception ");} String returnCode = (String) resultMap.get (" return_code "); String returnMsg = (String) resultMap.get (" return_msg ") If (returnCode.equalsIgnoreCase (PayContants.FAIL)) {throw new RuntimeException (returnMsg);} String result_code = (String) resultMap.get ("result_code"); if (result_code.equalsIgnoreCase (PayContants.FAIL)) {throw new RuntimeException (resultMap.get ("err_code_des"));} String trade_state = (String) resultMap.get ("trade_state"); return trade_state;}}
WeChatPayController:
/ * * WeChat Pay interface * / @ Controllerpublic class WxPayController {@ Autowired WeChatPayServcie weChatPayServcie / payID * * WeChat Pay issued an order * payID does not need to send a random number generated by itself within 32 digits. To ensure that it does not repeat * the amount of totalFee must be judged to determine whether the payment is consistent with the database * / @ RequestMapping ("pay") @ ResponseBody public Map toWxpay (HttpServletRequest httpRequest,String payId, String totalFee, String body {System.out.println ("start WeChat Pay...") Map map = new HashMap (); String nonce_str = UUID.randomUUID (). ToString (). Trim (). ReplaceAll ("-", "); / / generate a payment record / / splice payment parameter Map paramMap = new HashMap (); paramMap.put (" nonce_str ", nonce_str); paramMap.put (" prod_id ", payId); paramMap.put (" body ", body) ParamMap.put ("total_fee", totalFee); paramMap.put ("out_trade_no", payId); / / send a payment request and get the return parameters and QR code for payment and call the query interface Map returnMap = weChatPayServcie.getWxpayUrl (paramMap); httpRequest.setAttribute ("out_trade_no", payId); httpRequest.setAttribute ("total_fee", totalFee) / / code_url is the QR code URL, which can be put into the fodder QR code to generate Wechat QR code httpRequest.setAttribute ("code_url", returnMap.get ("code_url"); map.put ("out_trade_no", payId); map.put ("total_fee", String.valueOf (bigDecimal)); map.put ("code_url", returnMap.get ("code_url")); return map } / * query Wechat order * ot_trade_no is paid for * / @ RequestMapping ("query") @ ResponseBody public Root orderQuery (String out_trade_no) {return weixinPayServcie.orderQuery (queryCallbackForm.getOut_trade_no ()) } * WeChat Pay callback, this address is NOTYFLY_URL * / @ RequestMapping ("callback") public void notify_url (HttpServletRequest request, HttpServletResponse response) throws DocumentException, ServletException, IOException,Throwable {System.out.print ("WeChat Pay callback starts to obtain data") in Config; String inputLine; String notityXml = "" Try {while ((inputLine = request.getReader (). ReadLine ())! = null) {notityXml + = inputLine;} request.getReader (). Close ();} catch (Exception e) {WxUtil.sendXmlMessage (request,response, PayContants.FAIL); throw new RuntimeException ("callback data xml acquisition failed!") ;} if (StringUtils.isEmpty (notityXml)) {WxUtil.sendXmlMessage (request,response, PayContants.FAIL); throw new RuntimeException ("callback xml is empty!") ;} Map resultMap = XMLParse.parseXmlMap (notityXml); String returnCode = (String) resultMap.get ("return_code"); String returnMsg = (String) resultMap.get ("return_msg"); if (returnCode.equalsIgnoreCase (PayContants.FAIL)) {WxUtil.sendXmlMessage (request,response, PayContants.FAIL); throw new RuntimeException (returnMsg);} String resultCode = (String) resultMap.get ("result_code") If (resultCode.equalsIgnoreCase (PayContants.FAIL)) {WxUtil.sendXmlMessage (request,response, PayContants.FAIL); throw new RuntimeException (resultMap.get ("err_code_des"));} SortedMap paramMap = new TreeMap (); paramMap.put ("appid", resultMap.get ("appid")); paramMap.put ("mch_id", resultMap.get ("mch_id")) ParamMap.put ("nonce_str", resultMap.get ("nonce_str"); paramMap.put ("body", resultMap.get ("body")); paramMap.put ("openid", resultMap.get ("openid")); paramMap.put ("is_subscribe", resultMap.get ("is_subscribe")); paramMap.put ("trade_type", resultMap.get ("trade_type")) ParamMap.put ("bank_type", resultMap.get ("bank_type"); paramMap.put ("total_fee", resultMap.get ("total_fee")); paramMap.put ("fee_type", resultMap.get ("fee_type")); paramMap.put ("cash_fee", resultMap.get ("cash_fee")); paramMap.put ("transaction_id", resultMap.get ("transaction_id")) ParamMap.put ("out_trade_no", resultMap.get ("out_trade_no"); paramMap.put ("time_end", resultMap.get ("time_end")); paramMap.put ("return_code", resultMap.get ("return_code")); paramMap.put ("return_msg", resultMap.get ("return_msg")); paramMap.put ("result_code", resultMap.get ("result_code")) String out_trade_no = (String) resultMap.get ("out_trade_no"); String sign = SignUtil.createSign (paramMap,WxPayConfig.KEY); String mySign = (String) resultMap.get ("sign"); / / callback must verify the signature in case the data is tampered with if (sign.equals (mySign)) {System.out.println ("callback signature verification successful!") ; / / modify the business logic to change the payment status to paid} WxUtil.sendXmlMessage (request,response, PayContants.SUCCESS);} else {WxUtil.sendXmlMessage (request,response, PayContants.FAIL); throw new RuntimeException ("signature inconsistent!") ;}
WxUtil:
Package com.ys.commons.utils.pay; import java.io.BufferedWriter;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.InetAddress;import java.net.UnknownHostException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; / / Wechat tool class public class WxUtil {/ / get the current IP public static String getIp () {try {String spbill_create_ip = InetAddress.getLocalHost () .getHostAddress () Return spbill_create_ip;} catch (UnknownHostException var2) {var2.printStackTrace (); return "failed to get IP...";}} / / output xml format public static void sendXmlMessage (HttpServletRequest request, HttpServletResponse response, String content) {try {String contentXml = ""; OutputStream os = response.getOutputStream (); BufferedWriter resBr = new BufferedWriter (new OutputStreamWriter (os)); resBr.write (contentXml) ResBr.flush (); resBr.close ();} catch (IOException var6) {var6.printStackTrace ();} / / generate sign signature public static String createSign (SortedMap packageParams, String KEY) {StringBuffer sb = new StringBuffer (); Set es = packageParams.entrySet (); Iterator it = es.iterator (); while (it.hasNext ()) {Entry entry = (Entry) it.next () String k = (String) entry.getKey (); String v = (String) entry.getValue (); if (null! = v & &! ".equals (v) & &!" sign ".equals (k) & &!" key ".equals (k)) {sb.append (k +" = "+ v +" & ");}} sb.append (" key= "+ KEY) String sign = MD5Util.MD5Encode (sb.toString (), "UTF-8"). ToUpperCase (); return sign;} / / convert map to xml public static String parseMapXML (SortedMap map) {String xmlResult = "; StringBuffer sb = new StringBuffer (); sb.append ("); Iterator var3 = map.keySet (). Iterator (); while (var3.hasNext ()) {String key = (String) var3.next (); String value = "" Sb.append ("+ value +"); System.out.println ();} sb.append ("); xmlResult = sb.toString (); return xmlResult;} / convert xml to map public static Map parseXmlMap (String xml) throws DocumentException {Document document = DocumentHelper.parseText (xml); Element root = document.getRootElement (); List elementList = root.elements (); Map map = new HashMap (); Iterator var5 = elementList.iterator () While (var5.hasNext ()) {Element e = (Element) var5.next (); map.put (e.getName (), e.getText ());} return map;}}
To send a request, you need to recommend a very useful tool, in which various commonly used tools are encapsulated with hutool. If you want to copy the code directly, you also need to introduce the maven library of this tool.
The above is all the contents of this article "sample Analysis of Wechat Navicat payments developed by Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.