In this paper, we share the example code of Java wechat public account payment for your reference. The specific content is as follows

Before you start, prepare: appID, merchant number, merchant key.

Tools:

MD5Util.java

`package` `com.yiexpress.core.utils.wechat; ` `import` `java.security.MessageDigest; ` `/** ** MD5 tool class */`

`public` `class` `MD5Util {`

`public` `final` `static` `String MD5(String s) {`

`char` `hexDigits[]={``'0'` `, ` `'1'` `, ` `'2'` `, ` `'3'` `, ` `'4'` `, ` `'5'` `, ` `'6'` `, ` `'7'` `, ` `'8'` `, ` `'9'` `, ` `'A'` `, ` `'B'` `, ` `'C'` `, ` `'D'` `, ` `'E'` `, ` `'F'` `}; ` `try` `{` `byte``[] btInput = s.getBytes(); ` `MessageDigest mdInst = MessageDigest.getInstance(``"MD5"` `); ` `mdInst.update(btInput); ` `byte``[] md = mdInst.digest(); ` `int` `j = md.length; ` `char` `str[] =` `new` `char``[j *` `2` `]; ` `int` `k =` `0` `; ` `for` ` (` `int` `i =` `0` `; i < j; i++) {` `byte` `byte0 = md[i]; ` `str[k++] = hexDigits[byte0 >>>` `4` ` & ` `0xf` `]; ` `str[k++] = hexDigits[byte0 &` `0xf` `]; ` `}` `String md5Str =` `new` `String(str); ` `return` `md5Str; ` `} ` `catch` `(Exception e) {` `e.printStackTrace(); ` `return` `null``; ` `} ` `} ` ` `}Copy the code

SapUtils.java

`package` `com.yiexpress.core.utils; ` `import` `java.lang.reflect.*; ` `import` `java.util.List; ` `import` `java.io.IOException; ` `import` `java.io.StringWriter; ` `import` `org.dom4j.Document; ` `import` `org.dom4j.DocumentHelper; ` `import` `org.dom4j.Element; ` `import` `org.dom4j.io.OutputFormat; ` `import` `org.dom4j.io.XMLWriter; ` `import` `org.slf4j.Logger; ` `import` `org.slf4j.LoggerFactory; ` `import` `org.springframework.util.StringUtils; ` `public` `class` `SapUtils {`

`private` `static` `final` `Logger logger = LoggerFactory.getLogger(SapUtils.``class``); ` `/** Convert javabeans into XML files according to reflection ' '* with class name first tag, all attributes as second nodes, and put the corresponding values, If the property is empty, the object passed in by the familiar '* @param dto' '* @param operationName' '* @return' '*/' is not put in`

`public` `static` `String formatToXml(Object dto,String operationName){`

`logger.info(``"Parse data in the specified XML document format for the current class {}"``,dto.getClass().getName()); ` `logger.info(``"The current synchronization method is {}"``,operationName); ` `String result =` `null``; ` `Field fields[]=dto.getClass().getDeclaredFields(); ` `//dto is the entity class name

`//DocumentHelper provides methods for creating Document objects`Document document = DocumentHelper.createDocument(); ` `// Add node information`String className=dto.getClass().getName(); ` `// The name of the operation`Element rootElement = document.addElement(operationName); ` `try` `{`

`Field.setAccessible(fields,` `true` `); ` `for` ` (` `int` `i =` `0` `; i < fields.length; i++) {` `// Add node information

`if` ` (! StringUtils.isEmpty(fields[i].get(dto))){` `Class<? > type = fields[i].getType(); ` `// If it is list '

`if``(type == List.``class``){` `String listName = fields[i].getName(); ` `createElement(rootElement, fields[i].get(dto),listName); ` `} ` `else``{` `Element element = rootElement.addElement(fields[i].getName()); ` `element.setText((String) fields[i].get(dto)); ' '} ' '} ' ' '} ' '// Set the XML document format`OutputFormat outputFormat = OutputFormat.createPrettyPrint(); ` `// Set the XML encoding mode, that is, save the XML document to the String with the specified encoding mode, which can also be specified as GBK or ISO8859-1 '

`outputFormat.setEncoding(``"UTF-8"` `); ` `// outputFormat.setSuppressDeclaration(true); // Whether to produce the XML header '

`outputFormat.setIndent(``true` `); ` `// Set whether to indent

`outputFormat.setIndent(``""` `); ` `// Indent 'with four Spaces

`outputFormat.setNewlines(``true` `); ` `// Sets whether to break a line`StringWriter stringWriter =``null``; ` `// Writer fileWriter =null; `

`// xmlWriter is a tool for writing XML documents to strings`XMLWriter xmlWriter =` `null``; ` `try` ` {` `// stringWriter strings are used to hold XML documents'

`stringWriter =` `new` `StringWriter(); ` `// fileWriter = new FileWriter("D:\\modu11le.xml"); `

`// xmlWriter is a tool for writing XML documents to strings

`xmlWriter =` `new` `XMLWriter(stringWriter, outputFormat); ` `// Write the created XML document to the string '`xmlWriter.write(document); ` `//fileWriter.write(stringWriter.toString()); ``result=stringWriter.toString(); ` `} ` `catch` `(IOException e) {`

`logger.error(``"Failed to write data"` `); ` `throw` `new` `RuntimeException(``"Failed to write data"``+e); ` `}``finally``{` `try` ` {` `if``(xmlWriter! =``null``){` `xmlWriter.flush(); ` `xmlWriter.close(); ` `} ` `/* if(fileWriter! =null){` `fileWriter.flush(); ` `fileWriter.close(); ` `} * /`

`} catch (IOException e) {`

`logger.error("Error closing output outflow"); ` `throw new RuntimeException("Error closing output outflow"+e); ` `} ` `} ` `}catch (Exception e) {`

`logger.error("Failed to add XML node"+e); ` `}` `logger.error("Finished converting XML"); ` `returnresult; ` `} ` `/** '* Adds a list' * @param Element '* @param object' * @param name '* @return' * @throws IllegalArgumentException '  `* @throws IllegalAccessException` `*/`

`public` `static` `Element createElement(Element element ,Object object,String name )` `throws` `IllegalArgumentException, IllegalAccessException{` `Element nameElement = element.addElement(name); ` `List info = (List)object; ` `for` ` (` `int` `j=` `0` `; j<info.size(); j++){` `// Add the row label '

`Element rowElement = nameElement.addElement(``"row"` `); ` `// Add the familiarity of the object`Field fields[]=info.get(j).getClass().getDeclaredFields(); ` `//dto is the entity class name

`Field.setAccessible(fields,` `true` `); ` `for` ` (` `int` `i =` `0` `; i < fields.length; i++) {` `// Add node information

`if` ` (! StringUtils.isEmpty(fields[i].get(info.get(j)))){` `Element childElement = rowElement.addElement(fields[i].getName()); ` `childElement.setText((String) fields[i].get(info.get(j))); ' '} ' '} ' ' '} ' 'return` `element; ` ` `} ` `}Copy the code

UnifiedOrderRequest.java

`package` `com.yiexpress.core.utils.wechat; ` `public` `class` `UnifiedOrderRequest {`

`private` `String appid; ` `// Public account ID '

`private` `String mch_id; ` `// Merchant number '

`private` `String device_info; ` `// Device id No

`private` `String nonce_str; ` `// Random string '

`private` `String sign; ` `/ / signature `

`private` `String sign_type; ` `// Signature type '

`private` `String body; ` `// Product description '

`private` `String detail; ` `// Merchandise details'

`private` `String attach; ` `// Attach data '

`private` `String out_trade_no; ` `// Merchant order number '

`private` `String fee_type; ` `// Pricing currency

`private` `String total_fee; ` `// List price '

`private` `String spbill_create_ip; ` `// Terminal IP '

`private` `String time_start; ` `// Start time of transaction '

`private` `String time_expire; ` `// Transaction end time '

`private` `String goods_tag; ` `// Order discount mark '

`private` `String notify_url; ` `// Notify address '

`private` `String trade_type; ` `// Transaction type '

`private` `String product_id; ` `/ / ID ` goods

`private` `String limit_pay; ` `// Specify payment method '

`private` `String openid; ` `// User id '

`public` `String getAppid(a) {`

`return` `appid; ` `} ` `public` `void` `setAppid(String appid) {`

`this``.appid = appid; ` `} ` `public` `String getMch_id(a) {`

`return` `mch_id; ` `} ` `public` `void` `setMch_id(String mch_id) {`

`this``.mch_id = mch_id; ` `} ` `public` `String getDevice_info(a) {`

`return` `device_info; ` `} ` `public` `void` `setDevice_info(String device_info) {`

`this``.device_info = device_info; ` `} ` `public` `String getNonce_str(a) {`

`return` `nonce_str; ` `} ` `public` `void` `setNonce_str(String nonce_str) {`

`this``.nonce_str = nonce_str; ` `} ` `public` `String getSign(a) {`

`return` `sign; ` `} ` `public` `void` `setSign(String sign) {`

`this``.sign = sign; ` `} ` `public` `String getSign_type(a) {`

`return` `sign_type; ` `} ` `public` `void` `setSign_type(String sign_type) {`

`this``.sign_type = sign_type; ` `} ` `public` `String getBody(a) {`

`return` `body; ` `} ` `public` `void` `setBody(String body) {`

`this``.body = body; ` `} ` `public` `String getDetail(a) {`

`return` `detail; ` `} ` `public` `void` `setDetail(String detail) {`

`this``.detail = detail; ` `} ` `public` `String getAttach(a) {`

`return` `attach; ` `} ` `public` `void` `setAttach(String attach) {`

`this``.attach = attach; ` `} ` `public` `String getOut_trade_no(a) {`

`return` `out_trade_no; ` `} ` `public` `void` `setOut_trade_no(String out_trade_no) {`

`this``.out_trade_no = out_trade_no; ` `} ` `public` `String getFee_type(a) {`

`return` `fee_type; ` `} ` `public` `void` `setFee_type(String fee_type) {`

`this``.fee_type = fee_type; ` `} ` `public` `String getTotal_fee(a) {`

`return` `total_fee; ` `} ` `public` `void` `setTotal_fee(String total_fee) {`

`this``.total_fee = total_fee; ` `} ` `public` `String getSpbill_create_ip(a) {`

`return` `spbill_create_ip; ` `} ` `public` `void` `setSpbill_create_ip(String spbill_create_ip) {`

`this``.spbill_create_ip = spbill_create_ip; ` `} ` `public` `String getTime_start(a) {`

`return` `time_start; ` `} ` `public` `void` `setTime_start(String time_start) {`

`this``.time_start = time_start; ` `} ` `public` `String getTime_expire(a) {`

`return` `time_expire; ` `} ` `public` `void` `setTime_expire(String time_expire) {`

`this``.time_expire = time_expire; ` `} ` `public` `String getGoods_tag(a) {`

`return` `goods_tag; ` `} ` `public` `void` `setGoods_tag(String goods_tag) {`

`this``.goods_tag = goods_tag; ` `} ` `public` `String getNotify_url(a) {`

`return` `notify_url; ` `} ` `public` `void` `setNotify_url(String notify_url) {`

`this``.notify_url = notify_url; ` `} ` `public` `String getTrade_type(a) {`

`return` `trade_type; ` `} ` `public` `void` `setTrade_type(String trade_type) {`

`this``.trade_type = trade_type; ` `} ` `public` `String getProduct_id(a) {`

`return` `product_id; ` `} ` `public` `void` `setProduct_id(String product_id) {`

`this``.product_id = product_id; ` `} ` `public` `String getLimit_pay(a) {`

`return` `limit_pay; ` `} ` `public` `void` `setLimit_pay(String limit_pay) {`

`this``.limit_pay = limit_pay; ` `} ` `public` `String getOpenid(a) {`

`return` `openid; ` `} ` `public` `void` `setOpenid(String openid) {`

`this``.openid = openid; ` ` `} ` `}Copy the code

UnifiedOrderRespose.java

`package` `com.yiexpress.core.utils.wechat; ` `public` `class` `UnifiedOrderRespose {`

`private` `String return_code; ` `// Return status code '

`private` `String return_msg; ` `// Return information '

`private` `String appid; ` `// Public account ID '

`private` `String mch_id; ` `// Merchant number '

`private` `String device_info; ` `// Device number '

`private` `String nonce_str; ` `// Random string '

`private` `String sign; ` `/ / signature `

`private` `String result_code; ` `// Business result '

`private` `String err_code; ` `// Error code '

`private` `String err_code_des; ` `// Error code description '

`private` `String trade_type; ` `// Transaction type '

`private` `String prepay_id; ` `// Pre-pay transaction session id '

`private` `String code_url; ` `// Qr code link '

`public` `String getReturn_code(a) {`

`return` `return_code; ` `} ` `public` `void` `setReturn_code(String return_code) {`

`this``.return_code = return_code; ` `} ` `public` `String getReturn_msg(a) {`

`return` `return_msg; ` `} ` `public` `void` `setReturn_msg(String return_msg) {`

`this``.return_msg = return_msg; ` `} ` `public` `String getAppid(a) {`

`return` `appid; ` `} ` `public` `void` `setAppid(String appid) {`

`this``.appid = appid; ` `} ` `public` `String getMch_id(a) {`

`return` `mch_id; ` `} ` `public` `void` `setMch_id(String mch_id) {`

`this``.mch_id = mch_id; ` `} ` `public` `String getDevice_info(a) {`

`return` `device_info; ` `} ` `public` `void` `setDevice_info(String device_info) {`

`this``.device_info = device_info; ` `} ` `public` `String getNonce_str(a) {`

`return` `nonce_str; ` `} ` `public` `void` `setNonce_str(String nonce_str) {`

`this``.nonce_str = nonce_str; ` `} ` `public` `String getSign(a) {`

`return` `sign; ` `} ` `public` `void` `setSign(String sign) {`

`this``.sign = sign; ` `} ` `public` `String getResult_code(a) {`

`return` `result_code; ` `} ` `public` `void` `setResult_code(String result_code) {`

`this``.result_code = result_code; ` `} ` `public` `String getErr_code(a) {`

`return` `err_code; ` `} ` `public` `void` `setErr_code(String err_code) {`

`this``.err_code = err_code; ` `} ` `public` `String getErr_code_des(a) {`

`return` `err_code_des; ` `} ` `public` `void` `setErr_code_des(String err_code_des) {`

`this``.err_code_des = err_code_des; ` `} ` `public` `String getTrade_type(a) {`

`return` `trade_type; ` `} ` `public` `void` `setTrade_type(String trade_type) {`

`this``.trade_type = trade_type; ` `} ` `public` `String getPrepay_id(a) {`

`return` `prepay_id; ` `} ` `public` `void` `setPrepay_id(String prepay_id) {`

`this``.prepay_id = prepay_id; ` `} ` `public` `String getCode_url(a) {`

`return` `code_url; ` `} ` `public` `void` `setCode_url(String code_url) {`

`this``.code_url = code_url; ` ` `} ` `}Copy the code

WXPayConstants.java

`package` `com.yiexpress.core.utils.wechat; ` `public` `class` `WXPayConstants {`

`public` `enum` `SignType {`

`MD5, HMACSHA256`

`}`

`public` `static` `final` `String FAIL   =` `"FAIL"` `; ` `public` `static` `final` `String SUCCESS =` `"SUCCESS"` `; ` `public` `static` `final` `String HMACSHA256 =` `"HMAC-SHA256"` `; ` `public` `static` `final` `String MD5 =` `"MD5"` `; ` `public` `static` `final` `String FIELD_SIGN =` `"sign"` `; ` `public` `static` `final` `String FIELD_SIGN_TYPE =` `"sign_type"` `; ` ` `}Copy the code

WXPayUtil.java

`package` `com.yiexpress.core.utils.wechat; ` `import` `java.io.BufferedOutputStream; ` `import` `java.io.BufferedReader; ` `import` `java.io.ByteArrayInputStream; ` `import` `java.io.InputStream; ` `import` `java.io.InputStreamReader; ` `import` `java.io.StringWriter; ` `import` `java.io.Writer; ` `import` `java.net.HttpURLConnection; ` `import` `java.net.URL; ` `import` `java.util.*; ` `import` `java.security.MessageDigest; ` `import` `org.w3c.dom.Node; ` `import` `org.w3c.dom.NodeList; ` `import` `com.yiexpress.core.utils.SapUtils; ` `import` `com.yiexpress.core.utils.XmlUtil; ` `import` `com.yiexpress.core.utils.wechat.WXPayConstants.SignType; ` `import` `javax.crypto.Mac; ` `import` `javax.crypto.spec.SecretKeySpec; ` `import` `javax.xml.parsers.DocumentBuilder; ` `import` `javax.xml.parsers.DocumentBuilderFactory; ` `import` `javax.xml.transform.OutputKeys; ` `import` `javax.xml.transform.Transformer; ` `import` `javax.xml.transform.TransformerFactory; ` `import` `javax.xml.transform.dom.DOMSource; ` `import` `javax.xml.transform.stream.StreamResult; ` `import` `org.jdom2.Document; ` `import` `org.jdom2.Element; ` `import` `org.jdom2.input.SAXBuilder; ` `import` `org.slf4j.Logger; ` `import` `org.slf4j.LoggerFactory; ` `/** ** payment tool class */`

`public` `class` `WXPayUtil {`

`private` `static` `Logger log= LoggerFactory.getLogger(WXPayUtil.``class``); ` `/** ** Generate order object information * @param orderId Order number * @param appId wechat appId * @param McH_id Wechat assigned merchant ID * @param Body Payment introduction body ** @param price Paid price (magnify 100 times) * @param spbill_create_IP Terminal IP * @param notify_URL Asynchronous direct result notification interface address * @param noncESTr * @return` `*/`

`public` `static` `Map<String,Object> createOrderInfo(Map<String, String> requestMap,String shopKey) {` `// Generate the order object '

`UnifiedOrderRequest unifiedOrderRequest =` `new` `UnifiedOrderRequest(); `

`unifiedOrderRequest.setAppid(requestMap.get(``"appId"` `)); ` `// Public account ID '

`unifiedOrderRequest.setBody(requestMap.get(``"body"` `)); ` `// Product description '

`unifiedOrderRequest.setMch_id(requestMap.get(``"mch_id"` `)); ` `// Merchant number '

`unifiedOrderRequest.setNonce_str(requestMap.get(``"noncestr"` `)); ` `// Random string '

`unifiedOrderRequest.setNotify_url(requestMap.get(``"notify_url"` `)); ` `// Notify address '

`unifiedOrderRequest.setOpenid(requestMap.get(``"userWeixinOpenId"` `)); ` `unifiedOrderRequest.setDetail(requestMap.get(``"detail"` `)); ` `/ / ` for details

`unifiedOrderRequest.setOut_trade_no(requestMap.get(``"out_trade_no"` `)); ` `// Merchant order number '

`unifiedOrderRequest.setSpbill_create_ip(requestMap.get(``"spbill_create_ip"` `)); ` `// Terminal IP '

`unifiedOrderRequest.setTotal_fee(requestMap.get(``"payMoney"` `)); ` `// The amount needs to be 100 times larger :1 represents 0.01 'at the time of payment

`unifiedOrderRequest.setTrade_type(``"JSAPI"` `); ` `//JSAPI-- public account payment, NATIVE-- NATIVE scan code payment, APP-- APP payment

`SortedMap<String, String> packageParams =` `new` `TreeMap<String, String>(); `

`packageParams.put(``"appid"``, unifiedOrderRequest.getAppid()); `

`packageParams.put(``"body"``, unifiedOrderRequest.getBody()); `

`packageParams.put(``"mch_id"``, unifiedOrderRequest.getMch_id()); `

`packageParams.put(``"nonce_str"``, unifiedOrderRequest.getNonce_str()); `

`packageParams.put(``"notify_url"``, unifiedOrderRequest.getNotify_url()); ` `packageParams.put(``"openid"``, unifiedOrderRequest.getOpenid()); ` `packageParams.put(``"detail"``, unifiedOrderRequest.getDetail()); ` `packageParams.put(``"out_trade_no"``, unifiedOrderRequest.getOut_trade_no()); `

`packageParams.put(``"spbill_create_ip"``, unifiedOrderRequest.getSpbill_create_ip()); `

`packageParams.put(``"total_fee"``, unifiedOrderRequest.getTotal_fee()); `

`packageParams.put(``"trade_type"``, unifiedOrderRequest.getTrade_type()); ` `try` `{` `unifiedOrderRequest.setSign(generateSignature(packageParams,shopKey)); ` `/ / signature ``} ` `catch` `(Exception e) {` `e.printStackTrace(); ` `} ` `// Convert the order object to XML format '

`String orderstr=SapUtils.formatToXml(unifiedOrderRequest,``"xml"``).replace(``"
      "` `, ` `""` `); ` `log.debug(``"Encapsulated unified single request data:"``+orderstr.replace(``"__"` `, ` `"_"` `)); ` `Map<String,Object> responseMap =` `new` `HashMap<String,Object>(); ` `responseMap.put(``"orderInfo_toString"``, orderstr.replace(``"__"` `, ` `"_"` `)); ` `responseMap.put(``"unifiedOrderRequest"``,unifiedOrderRequest); ` `return` `responseMap; `

`} `

`public` `static` `void` `main(String[] args) {`

`// UnifiedOrderRequest ut=new UnifiedOrderRequest(); `

`// ut.setAppid("wx1234156789"); `

`// ut.setBody(" content body"); `

`// ut.setmch_id (" merchant id "); `

`// ut.setnonce_str (" random string "); `

`// ut.setnotify_url (" callback address "); `

`// ut.setOpenid("openid"); `

`// ut.setdetail (" details "); `

`// ut.setout_trade_no (" order number "); `

`// ut.setspbill_create_ip (" terminal IP"); `

`// ut.settotal_fee (" fee "); `

`Ut.settrade_type (" call type JSAPI"); // ut.settrade_type (" call type JSAPI"); `

`// System.out.println("---"+SapUtils.formatToXml(ut,"xml")+"---"); `

`// UnifiedOrderRequest unifiedOrderRequest = new UnifiedOrderRequest(); `

`// unifiedOrderRequest.setAppid("dsfsdf"); // Public account ID '

`// unifiedOrderRequest.setBody("sdfsdf"); // Product description '

`// unifiedOrderRequest.setMch_id("sdfsd"); // Merchant number '

`// unifiedOrderRequest.setNonce_str("dfsd"); // Random string '

`// unifiedOrderRequest.setNotify_url("sdfdsf"); // Notify address '

`// unifiedOrderRequest.setOpenid("sdfsdf"); `

`/ / `

`// unifiedOrderRequest.setTrade_type("JSAPI"); //JSAPI-- public account payment, NATIVE-- NATIVE scan code payment, APP-- APP payment

`/ / `

`// System.out.println("---"+SapUtils.formatToXml(unifiedOrderRequest,"xml").replace("
       ", "") +" - "); `

`// String str="
      
       
        dsfsdf
       
       
        sdfsd
       
       
        dfsd
       sdfsdf
       
        sdfdsf
        
         JSAPI
        
        
         sdfsdf
        
       
      "; `

`// UnifiedOrderRequest s=SapUtils.getBeanByxml(str,UnifiedOrderRequest.class); `

`// System.out.println(s.getAppid()+"---"+s.getMch_id()+"--"+s.getFee_type()); ``} ` `/** ' '* generate signature' '@param appid_value' '* @param McH_id_value' '* @param productId' '* @param nonce_str_value' '* @param trade_type ` `* @param notify_url ` `* @param spbill_create_ip ` `* @param total_fee ` `* @param out_trade_no ` `* @return` `*/` 

`private` `static` `String createSign(UnifiedOrderRequest unifiedOrderRequest,String shopKey) {` `// Create a sortable map collection according to the rules

`SortedMap<String, String> packageParams =` `new` `TreeMap<String, String>(); `

`packageParams.put(``"appid"``, unifiedOrderRequest.getAppid()); `

`packageParams.put(``"body"``, unifiedOrderRequest.getBody()); `

`packageParams.put(``"mch_id"``, unifiedOrderRequest.getMch_id()); `

`packageParams.put(``"nonce_str"``, unifiedOrderRequest.getNonce_str()); `

`packageParams.put(``"notify_url"``, unifiedOrderRequest.getNotify_url()); `

`packageParams.put(``"out_trade_no"``, unifiedOrderRequest.getOut_trade_no()); `

`packageParams.put(``"spbill_create_ip"``, unifiedOrderRequest.getSpbill_create_ip()); `

`packageParams.put(``"trade_type"``, unifiedOrderRequest.getTrade_type()); `

`packageParams.put(``"total_fee"``, unifiedOrderRequest.getTotal_fee()); `

`StringBuffer sb =` `new` `StringBuffer(); ` `Set es = packageParams.entrySet(); ` `// dictionary order

`Iterator it = es.iterator(); `

`while` `(it.hasNext()) { `

`Map.Entry entry = (Map.Entry) it.next(); `

`String k = (String) entry.getKey(); `

`String v = (String) entry.getValue(); `

`// Empty does not participate in the signature, parameter name is case sensitive '

`if` `(``null` `! = v && ! ` `""``.equals(v) && ! ` `"sign"``.equals(k) && ! ` `"key"``.equals(k)) { `

`sb.append(k +` `"="` `+ v +` `"&"` `); ' '} ' '} ' '// The second step is to splicekey, key setting path: wechat merchant platform (pay.weixin.qq.com)--> account setting -->API security --> key setting '

`sb.append(``"key="``+shopKey); ` `String sign = MD5Util.MD5(sb.toString()).toUpperCase(); ` `/ / the MD5 encryption `

`log.error(``"Signature generated in Mode 1 ="``+sign); ` `return` `sign; `

`} `

`/ / XML parsing `

`public` `static` `SortedMap<String, String> doXMLParseWithSorted(String strxml)` `throws` `Exception {  `

`strxml = strxml.replaceFirst(``"encoding=\".*\""` `, ` `"encoding=\"UTF-8\""` `); ` `if``(``null` `== strxml ||` `""``.equals(strxml)) {  `

`return` `null``;  `

`}  `

`SortedMap<String,String> m =` `new` `TreeMap<String,String>();   `

`InputStream in =` `new` `ByteArrayInputStream(strxml.getBytes(``"UTF-8"` `)); ` `SAXBuilder builder =` `new` `SAXBuilder();  `

`Document doc = builder.build(in);  `

`Element root = doc.getRootElement();  `

`List list = root.getChildren();  `

`Iterator it = list.iterator();  `

`while``(it.hasNext()) {  `

`Element e = (Element) it.next();  `

`String k = e.getName();  `

`String v =` `""` `; ` `List children = e.getChildren(); ` `if``(children.isEmpty()) { ` `v = e.getTextNormalize(); ` `} ` `else` `{  `

`v = getChildrenText(children);  `

`}  `

`m.put(k, v);  `

`}  `

`// Close the stream

`in.close();   `

`return` `m;  `

`}  `

`public` `static` `String getChildrenText(List children) {  `

`StringBuffer sb =` `new` `StringBuffer();  `

`if` ` (! children.isEmpty()) { ` `Iterator it = children.iterator(); ` `while``(it.hasNext()) {  `

`Element e = (Element) it.next();  `

`String name = e.getName();  `

`String value = e.getTextNormalize();  `

`List list = e.getChildren();  `

`sb.append(``"<"` `+ name +` `">"` `); ` `if` ` (!list.isEmpty()) {  `

`sb.append(getChildrenText(list));  `

`}  `

`sb.append(value);  `

`sb.append(``"< /"` `+ name +` `">"` `); ' '} ' '} ' 'return` `sb.toString();  `

`} `

`/ * * ` ` * adjustable unified order API ` ` * @ param orderInfo ` ` * @ return ` ` * /` 

`public` `static` `UnifiedOrderRespose httpOrder(String orderInfo,``int` `index) {`

`// Unified single interface address automatically ADAPTS to 1 in China 2 in Southeast Asia 3 in other '

`String[] urlList={``"[https://api.mch.weixin.qq.com/pay/unifiedorder](https://api.mch.weixin.qq.com/pay/unifiedorder)"` `, ` `"[https://apihk.mch.weixin.qq.com/pay/unifiedorder](https://apihk.mch.weixin.qq.com/pay/unifiedorder)"` `, ` `"[https://apius.mch.weixin.qq.com/pay/unifiedorder](https://apius.mch.weixin.qq.com/pay/unifiedorder) "` `}; ` `//String url = "[https://api.mch.weixin.qq.com/pay/unifiedorder](https://api.mch.weixin.qq.com/pay/unifiedorder)"; `

`try` `{ `

`HttpURLConnection conn = (HttpURLConnection)` `new` `URL(urlList[index]).openConnection(); `

`// Add data '

`conn.setRequestMethod(``"POST"` `); ` `conn.setDoOutput(``true` `); ` `BufferedOutputStream buffOutStr =` `new` `BufferedOutputStream(conn.getOutputStream());  `

`buffOutStr.write(orderInfo.getBytes(``"UTF-8"` `)); ` `buffOutStr.flush(); ` `buffOutStr.close(); ` `// Get the input stream

`BufferedReader reader =` `new` `BufferedReader(``new` `InputStreamReader(conn.getInputStream(),` `"UTF-8"` `)); ` `String line =` `null``; ` `StringBuffer sb =` `new` `StringBuffer();  `

`while``((line = reader.readLine())! =` `null``){ ` `sb.append(line); ` `} ` `// XML to object '

`UnifiedOrderRespose unifiedOrderRespose =XmlUtil.getBeanByxml(sb.toString(),UnifiedOrderRespose.``class``); `

`return` `unifiedOrderRespose; ` `} ` `catch` `(Exception e) { `

`e.printStackTrace(); `

`} `

`return` `null``; ` `} ` `/** ** XML format string converted to Map ** @param strXML XML string * @return Map after XML data conversion * @throws Exception */`

`public` `static` `Map<String, String> xmlToMap(String strXML)` `throws` `Exception {`

`try` `{`

`Map<String, String> data =` `new` `HashMap<String, String>(); ` `DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); ` `DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); ` `InputStream stream =` `new` `ByteArrayInputStream(strXML.getBytes(``"UTF-8"` `)); ` `org.w3c.dom.Document doc = documentBuilder.parse(stream); ` `doc.getDocumentElement().normalize(); ` `NodeList nodeList = doc.getDocumentElement().getChildNodes(); ` `for` ` (` `int` `idx =` `0` `; idx < nodeList.getLength(); ++idx) {` `Node node = nodeList.item(idx); ` `if` `(node.getNodeType() == Node.ELEMENT_NODE) {` `org.w3c.dom.Element element = (org.w3c.dom.Element) node; ` `data.put(element.getNodeName(), element.getTextContent()); ` `} ` `} ` `try` `{` `stream.close(); ` `} ` `catch` `(Exception ex) {`

`// do nothing``} ` `return` `data; ` `} ` `catch` `(Exception ex) {`

`WXPayUtil.getLogger().warn(``"Invalid XML, can not convert to map. Error message: {}. XML content: {}"``, ex.getMessage(), strXML); ` `throw` `ex; ` `} ` `} ` `/** ** Converts a Map to an XML string ** @param data Data of the Map type * @return An XML string * @throws Exception */`

`public` `static` `String mapToXml(Map<String, String> data)` `throws` `Exception {` `DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); ` `DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder(); ` `org.w3c.dom.Document document = documentBuilder.newDocument(); ` `org.w3c.dom.Element root = document.createElement(``"xml"` `); ` `document.appendChild(root); ` `for` `(String key: data.keySet()) {` `String value = data.get(key); ` `if` `(value ==` `null``) {`

`value =` `""` `; ` `}` `value = value.trim(); ` `org.w3c.dom.Element filed = document.createElement(key); ` `filed.appendChild(document.createTextNode(value)); ` `root.appendChild(filed); ` `}` `TransformerFactory tf = TransformerFactory.newInstance(); ` `Transformer transformer = tf.newTransformer(); ` `DOMSource source =` `new` `DOMSource(document); ` `transformer.setOutputProperty(OutputKeys.ENCODING,` `"UTF-8"` `); ` `transformer.setOutputProperty(OutputKeys.INDENT,` `"yes"` `); ` `StringWriter writer =` `new` `StringWriter(); ` `StreamResult result =` `new` `StreamResult(writer); ` `transformer.transform(source, result); ` `String output = writer.getBuffer().toString(); ` `//.replaceAll("\n|\r", ""); `

`try` `{` `writer.close(); ` `} ` `catch` `(Exception ex) {`

`}`

`return` `output; ` `} ` `/** ** generates an XML format string with sign * @param data Map type data * @param key API key * @return XML with sign field */`

`public` `static` `String generateSignedXml(` `final` `Map<String, String> data, String key)` `throws` `Exception {`

`return` `generateSignedXml(data, key, SignType.MD5); ` `} ` `/** ** Generates an XML format string with sign * @param data Map type data * @param key API key * @param signType Signature type * @return XML ' '*/ with the sign field`

`public` `static` `String generateSignedXml(` `final` `Map<String, String> data, String key, SignType signType)` `throws` `Exception {` `String sign = generateSignature(data, key, signType); ` `data.put(WXPayConstants.FIELD_SIGN, sign); ` `return` `mapToXml(data); ` `} ` `/** check whether the signature is correct ** * @param xmlStr XML format data * @param key API key * @return Check whether the signature is correct * @throws Exception */`

`public` `static` `boolean` `isSignatureValid(String xmlStr, String key)` `throws` `Exception {` `Map<String, String> data = xmlToMap(xmlStr); ` `if` ` (! data.containsKey(WXPayConstants.FIELD_SIGN) ) {` `return` `false` `; ` `}` `String sign = data.get(WXPayConstants.FIELD_SIGN); ` `return` `generateSignature(data, key).equals(sign); ` `} ` `/** ' '* To check whether the signature is correct, the sign field must be included, otherwise return false. Use MD5 signature. * @param data Map data * @param key API key * @RETURN Check whether the signature is correct * @throws Exception */`

`public` `static` `boolean` `isSignatureValid(Map<String, String> data, String key)` `throws` `Exception {`

`return` `isSignatureValid(data, key, SignType.MD5); ` `} ` `/** ' '* To check whether the signature is correct, the sign field must be included, otherwise return false. * @param data Map data * @param KEY API key * @param signType Signature type * @RETURN Whether the signature is correct * @throws Exception */`

`public` `static` `boolean` `isSignatureValid(Map<String, String> data, String key, SignType signType)` `throws` `Exception {`

`if` ` (! data.containsKey(WXPayConstants.FIELD_SIGN) ) {` `return` `false` `; ` `}` `String sign = data.get(WXPayConstants.FIELD_SIGN); ` `return` `generateSignature(data, key, signType).equals(sign); ` `} ` `/ * * ` ` * generate signature ` ` * ` ` * @ param data to be signed data ` ` * @ param key API keys ` ` * @ return signature ` ` * /`

`public` `static` `String generateSignature(` `final` `Map<String, String> data, String key)` `throws` `Exception {`

`return` `generateSignature(data, key, SignType.MD5); ` `} ` `/** ' '* Generates a signature. Note That if the sign_type field is included, it must be consistent with the signType parameter. * @param data Data to be signed * @param key API key * @param signType Signature mode * @return signature */`

`public` `static` `String generateSignature(` `final` `Map<String, String> data, String key, SignType signType)` `throws` `Exception {` `Set<String> keySet = data.keySet(); ` `String[] keyArray = keySet.toArray(``new` `String[keySet.size()]); ` `Arrays.sort(keyArray); ` `StringBuilder sb =` `new` `StringBuilder(); ` `for` `(String k : keyArray) {`

`if` `(k.equals(WXPayConstants.FIELD_SIGN)) {`

`continue` `; ` `} ` `if` `(data.get(k).trim().length() >` `0` `) ` `// If the parameter value is empty, the signature is not involved

`sb.append(k).append(``"="``).append(data.get(k).trim()).append(``"&"` `); ` `}` `sb.append(``"key="``).append(key); ` `if` `(SignType.MD5.equals(signType)) {`

`return` `MD5(sb.toString()).toUpperCase(); ` `} ` `else` `if` `(SignType.HMACSHA256.equals(signType)) {`

`return` `HMACSHA256(sb.toString(), key); ` `} ` `else` ` {` `log.error(``Failed to obtain signature, cause of failure:``+String.format(``"Invalid sign_type: %s"``, signType)); ` `throw` `new` `Exception(String.format(``"Invalid sign_type: %s"``, signType)); ` `} ` `} ` `/** ** get random String Nonce Str * @return String Random String */`

`public` `static` `String generateNonceStr(a) {`

`return` `UUID.randomUUID().toString().replaceAll(``"-"` `, ` `""``).substring(``0` `, ` `32` `); ` `} ` `/** '* Map to XML data' */` 

`public` `static` `String GetMapToXML(Map<String,String> param){ `

`StringBuffer sb =` `new` `StringBuffer(); `

`sb.append(``"<xml>"` `); ` `for` `(Map.Entry<String,String> entry : param.entrySet()) {  `

`sb.append(``"<"``+ entry.getKey() +``">"` `); ` `sb.append(entry.getValue()); ` `sb.append(``"< /"``+ entry.getKey() +``">"` `); ` `} ` `sb.append(``"</xml>"` `); ` `return` `sb.toString(); `

`} `

`/ * * ` ` * generate MD5 ` ` * @ param data to be processed data ` ` * @ return MD5 results ` ` * /`

`public` `static` `String MD5(String data)` `throws` `Exception {`

`java.security.MessageDigest md = MessageDigest.getInstance(``"MD5"` `); ` `byte``[]array = md.digest(data.getBytes(``"UTF-8"` `)); ` `StringBuilder sb =` `new` `StringBuilder(); ` `for` `(``byte` `item : array) {`

`sb.append(Integer.toHexString((item &` `0xFF` `) | ` `0x100``).substring(``1` `, ` `3` `)); ` `} ` `return` `sb.toString().toUpperCase(); ` `} ` `/** * generates HMACSHA256 * @param data Data to be processed * @param key key * @return Encryption result * @throws Exception */`

`public` `static` `String HMACSHA256(String data, String key)` `throws` `Exception {`

`Mac sha256_HMAC = Mac.getInstance(``"HmacSHA256"` `); ` `SecretKeySpec secret_key =` `new` `SecretKeySpec(key.getBytes(``"UTF-8"` `), ` `"HmacSHA256"` `); ` `sha256_HMAC.init(secret_key); ` `byte``[]array = sha256_HMAC.doFinal(data.getBytes(``"UTF-8"` `)); ` `StringBuilder sb =` `new` `StringBuilder(); ` `for` `(``byte` `item : array) {`

`sb.append(Integer.toHexString((item &` `0xFF` `) | ` `0x100``).substring(``1` `, ` `3` `)); ` `} ` `return` `sb.toString().toUpperCase(); ` `} ` `/** * '* log' * @return '*/`

`public` `static` `Logger getLogger(a) {`

`Logger logger = LoggerFactory.getLogger(``"wxpay java sdk"` `); ` `return` `logger; ` `} ` `/** ** gets the current timestamp in seconds * @return */`

`public` `static` `long` `getCurrentTimestamp() {`

`return` `System.currentTimeMillis()/``1000` `; ` `} ` `/** ** gets the current timestamp in milliseconds * @return */`

`public` `static` `long` `getCurrentTimestampMs() {`

`return` `System.currentTimeMillis(); ` `} ` `/** * generates a uUID, which is used to identify an order or nonce_str '* @return' */`

`public` `static` `String generateUUID(a) {`

`return` `UUID.randomUUID().toString().replaceAll(``"-"` `, ` `""``).substring(``0` `, ` `32` `); ` `} ` `/** ' '* pay signature' '* @param TIMESTAMP' '* @param noncestr' '* @param Packages'' * @return ' '* @throws UnsupportedEncodingException ` `*/` 

`public` `static` `String paySign(String timestamp, String noncestr,String packages,String appId){ `

`Map<String, String> paras =` `new` `HashMap<String, String>(); `

`paras.put(``"appid"``, appId); `

`paras.put(``"timestamp"``, timestamp); `

`paras.put(``"noncestr"``, noncestr); `

`paras.put(``"package"``, packages); `

`paras.put(``"signType"` `, ` `"MD5"` `); ` `StringBuffer sb =` `new` `StringBuffer(); ` `Set es = paras.entrySet(); ` `// dictionary order

`Iterator it = es.iterator(); `

`while` `(it.hasNext()) { `

`Map.Entry entry = (Map.Entry) it.next(); `

`String k = (String) entry.getKey(); `

`String v = (String) entry.getValue(); `

`// Empty does not participate in the signature, parameter name is case sensitive '

`if` `(``null` `! = v && ! ` `""``.equals(v) && ! ` `"sign"``.equals(k) && ! ` `"key"``.equals(k)) { `

`sb.append(k +` `"="` `+ v +` `"&"` `); ` `} ` `} ` `String sign = MD5Util.MD5(sb.toString()).toUpperCase(); ` `/ / the MD5 encryption `

`return` `sign; ` ` `} ` `}Copy the code

XmlUtil.java

`package` `com.yiexpress.core.utils; ` `import` `java.io.StringReader; ` `import` `java.lang.reflect.Field; ` `import` `java.util.Date; ` `import` `org.dom4j.Document; ` `import` `org.dom4j.Element; ` `import` `org.dom4j.io.SAXReader; ` `import` `org.xml.sax.InputSource; ` `public` `class` `XmlUtil{`

`/** ** json data conversion object ** @param Element * the Element data to convert * @param pojo * The target object type to convert * @return The target object to convert * Throws Exception * The conversion fails */`

`@SuppressWarnings``(``"rawtypes"` `) ` `public` `static` `Object fromXmlToBean(Element rootElt, Class pojo)` `throws` `Exception{`

`// First get the fields defined by the POJO`Field[] fields = pojo.getDeclaredFields(); ` `// Dynamically generate poJO objects' from the incoming Class`Object obj = pojo.newInstance(); ` `for` `(Field field : fields)`

`{`

`// Set field accessible (must, otherwise error) '

`field.setAccessible(``true` `); ` `// Get the attribute name of the field`String name = field.getName(); ` `// This section raises an exception if the field does not exist in Element, and skips if it does. `

`try` `{` `rootElt.elementTextTrim(name); ` `} ` `catch` `(Exception ex)`

`{`

`continue` `; ` `} ` `if` `(rootElt.elementTextTrim(name) ! =` `null` `&& ! ` `""``.equals(rootElt.elementTextTrim(name)))`

`{`

`// Convert the value to the corresponding type based on the field type and set it into the generated object. `

`if` `(field.getType().equals(Long.``class``) || field.getType().equals(``long``.``class``))`

`{`

`field.set(obj, Long.parseLong(rootElt.elementTextTrim(name))); ` `} ` `else` `if` `(field.getType().equals(String.``class``))`

`{`

`field.set(obj, rootElt.elementTextTrim(name)); ` `} ` `else` `if` `(field.getType().equals(Double.``class``) || field.getType().equals(``double``.``class``))`

`{`

`field.set(obj, Double.parseDouble(rootElt.elementTextTrim(name))); ` `} ` `else` `if` `(field.getType().equals(Integer.``class``) || field.getType().equals(``int``.``class``))`

`{`

`field.set(obj, Integer.parseInt(rootElt.elementTextTrim(name))); ` `} ` `else` `if` `(field.getType().equals(java.util.Date.``class``))`

`{`

`field.set(obj, Date.parse(rootElt.elementTextTrim(name))); ` `} ` `else` ` {` `continue` `; ' '} ' '} ' ' '} ' 'return` `obj; ` `} ` `/ * * ` ` * transform XML format for the specified object ` ` * ` ` * @ param XML ` ` * @ return ` ` * /`

`@SuppressWarnings``(``"unchecked"` `) ` `public` `static` `<T> T getBeanByxml(String xml, Class<T> valueType) {` `T person =` `null``; ` `InputSource in =` `new` `InputSource(``new` `StringReader(xml)); ` `in.setEncoding(``"UTF-8"` `); ` `SAXReader reader =` `new` `SAXReader(); ` `Document document; ` `try` `{` `document = reader.read(in); ` `Element root = document.getRootElement(); ` `person = (T) XmlUtil.fromXmlToBean(root, valueType); ` `} ` `catch` `(Exception e) {`

`// TODO Auto-generated catch block``e.printStackTrace(); ` `System.out.println(``"Data parsing error"` `); ` `} ` `return` `person; ` ` `} ` `}Copy the code

Gets the pre-payment ID and signed controller

`package` `com.yiexpress.jerry.controller.ewe.wechat; ` `import` `java.util.HashMap; ` `import` `java.util.Map; ` `import` `java.util.SortedMap; ` `import` `java.util.TreeMap; ` `import` `javax.servlet.http.HttpServletRequest; ` `import` `org.slf4j.Logger; ` `import` `org.slf4j.LoggerFactory; ` `import` `org.springframework.stereotype.Controller; ` `import` `org.springframework.web.bind.annotation.RequestMapping; ` `import` `org.springframework.web.bind.annotation.RequestParam; ` `import` `org.springframework.web.bind.annotation.ResponseBody; ` `import` `com.yiexpress.core.utils.wechat.UnifiedOrderRequest; ` `import` `com.yiexpress.core.utils.wechat.UnifiedOrderRespose; ` `import` `com.yiexpress.core.utils.wechat.WXPayUtil; ` `/** ** wechat pay controller */`

`@Controller`

`@RequestMapping``(value =` `"/wxpay"` `) ` `public` `class` `WXPayController{`

`private` `static` `final` `Logger LOGGER = LoggerFactory.getLogger(WXPayController.``class``); ` `private` `String appId=``"Public main number AppID"` `; ` `// Public prefix appid '

`private` `String mchId=``"Merchant number"` `; ` `// Merchant number '

`private` `String apiKey=``"Merchant Key"` `; ` `// Merchant key '

`/ * * ` ` * get terminal IP ` ` * @ param request ` ` * @ return ` ` * /`

`public` `static` `String getIpAddr(HttpServletRequest request) { `

`String ip = request.getHeader(` `" x-forwarded-for "` `); `

`if` `(ip ==` `null` `|| ip.length() ==` `0` ` | | ` `" unknown "` `.equalsIgnoreCase(ip)) { `

`ip = request.getHeader(` `" Proxy-Client-IP "` `); `

`}  `

`if` `(ip ==` `null` `|| ip.length() ==` `0` ` | | ` `" unknown "` `.equalsIgnoreCase(ip)) { `

`ip = request.getHeader(` `" WL-Proxy-Client-IP "` `); `

`}  `

`if` `(ip ==` `null` `|| ip.length() ==` `0` ` | | ` `" unknown "` `.equalsIgnoreCase(ip)) { `

`ip = request.getRemoteAddr(); `

`}  `

`return` `ip; `

`} `

`/** ' '* return map' '* result-1' '*/`

`@RequestMapping``(``"/toPayInit"``)`

`@ResponseBody`

`public` `Map<String,Object> toPay(HttpServletRequest request,``@RequestParam``(value=``"payMoney"``,required=``true` `) ` `float` `payMoney,``@RequestParam``(value=``"openId"``,required=``true``) String openId,``@RequestParam``(value=``"orderId"``,required=``true``)String orderId){`

`Map<String,Object> map= ` `new` `HashMap<>(); ` `// Order number The random number currently produced is followed by the unique order number of the specified system

`// Check whether the order number exists`String noncestr = WXPayUtil.generateNonceStr(); ` `Map<String,String> requestMap =` `new` `HashMap<String, String>(); ` `requestMap.put(``"appId"``,appId); ` `requestMap.put(``"userWeixinOpenId"``,openId); ` `// The ETCA number was used as the merchant order number before, but now the bill number is automatically generated as 2018-10-25 Peter '

`//requestMap.put("out_trade_no",auShipmentBrief.getShipmentReference()); `

`requestMap.put(``"out_trade_no"` `, ` `"Order Number"` `); ` `requestMap.put(``"mch_id"``,mchId); ` `// Calculate the amount of wechat payment in minutes, for example: the actual payment is 1.23 yuan, the passed parameter is 123 '

`int` `money=``0` `; ` `try` `{`

`money=(``int``)(payMoney*``100` `); ` `} ` `catch` `(Exception e) {`

`map.put(``"result"` ` - ` `1` `); ` `map.put(``"msg"` `, ` `"Incorrect amount format"` `); ` `return` `map; ` `}` `requestMap.put(``"payMoney"``,money+``""` `); ` `requestMap.put(``"spbill_create_ip"``, getIpAddr(request)); ` `requestMap.put(``"notify_url"` `, ` `"Callback address"` `); ` `requestMap.put(``"noncestr"``, noncestr); ` `requestMap.put(``"body"` `, ` `"Wechat order bill payment"` `); ` `requestMap.put(``"detail"` `, ` `"Individual customers order and pay bills."` `); ` `Map<String,Object> requestInfo = WXPayUtil.createOrderInfo(requestMap,apiKey); ` `String orderInfo_toString = (String) requestInfo.get(``"orderInfo_toString"` `); ` `LOGGER.debug(``"Request Request string :"``+orderInfo_toString); ` `// Determine the return code

`UnifiedOrderRespose orderResponse = WXPayUtil.httpOrder(orderInfo_toString,``0` `); ` `// Call unified order interface '

`// Determine the case of timeout

`if``(orderResponse==``null` `|| orderResponse.getReturn_code()==``null` `|| (``"SUCCESS"``.equals(orderResponse.getReturn_code()) && (orderResponse.getErr_code()==``null` `||` `"SYSTEMERROR"``.equals(orderResponse.getErr_code())))){`

`orderResponse = WXPayUtil.httpOrder(orderInfo_toString,``1` `); ` `if``(orderResponse==``null` `|| orderResponse.getReturn_code()==``null` `|| (``"SUCCESS"``.equals(orderResponse.getReturn_code()) && (orderResponse.getErr_code()==``null` `||` `"SYSTEMERROR"``.equals(orderResponse.getErr_code())))){`

`orderResponse = WXPayUtil.httpOrder(orderInfo_toString,``2` `); ` `}` `}` `LOGGER.debug(``"Return field :==" {}"``,orderResponse); ` `// Code_URL 'will be returned only when both return_code and result_code are SUCCESS

`if``(``null``! =orderResponse &&` `"SUCCESS"``.equals(orderResponse.getReturn_code()) &&` `"SUCCESS"``.equals(orderResponse.getResult_code())){ ` `String timestamp = String.valueOf(WXPayUtil.getCurrentTimestamp()); ` `map.put(``"timestamp"``,timestamp); ` `map.put(``"noncestr"``,noncestr); ` `UnifiedOrderRequest unifiedOrderRequest = (UnifiedOrderRequest) requestInfo.get(``"unifiedOrderRequest"` `); ` `map.put(``"unifiedOrderRequest"``,unifiedOrderRequest); ` `SortedMap<String, String> packageParams =` `new` `TreeMap<String, String>(); `

`packageParams.put(``"appId"``,appId); `

`packageParams.put(``"signType"` `, ` `"MD5"` `); ` `packageParams.put(``"nonceStr"``, noncestr); `

`packageParams.put(``"timeStamp"``, timestamp); `

`String packages =` `"prepay_id="``+orderResponse.getPrepay_id(); ` `packageParams.put(``"package"``,packages); ` `String sign =` `null``; ` `try` ` {` `// Generate signature '`sign = WXPayUtil.generateSignature(packageParams,apiKey); ` `} ` `catch` `(Exception e) {`

`map.put(``"result"` ` - ` `1` `); ` `map.put(``"msg"` `, ` `"Payment signature information is abnormal"` `); ` `e.printStackTrace(); ` `} ` `if``(sign! =``null` `&& ! ` `""``.equals(sign)){`

`LOGGER.debug(``"------------ Payment signature:"``+sign+``"-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -"` `); ` `map.put(``"paySign"``,sign); ` `map.put(``"result"` `, ` `1` `); ` `map.put(``"appId"``,appId); ` `} ` `else` ` {` `map.put(``"result"` ` - ` `1` `); ` `map.put(``"msg"` `, ` `"Payment signature information is abnormal"` `); ` `} ` `map.put(``"prepay_id"``,orderResponse.getPrepay_id()); ` `return` `map; ` `} ` `else` ` {` `// failed

`if``(orderResponse! =``null``){` `String text =` `Error calling wechat Pay, return status code:``+orderResponse.getReturn_code()+``", return message:"``+orderResponse.getReturn_msg(); ` `if``(orderResponse.getErr_code()! =``null` `&& ! ` `""``.equals(orderResponse.getErr_code())){`

`text = text +``", error code:``+orderResponse.getErr_code()+``", error description:"``+orderResponse.getErr_code_des(); ` `}` `LOGGER.error(text); ` `} ` `else``{`

`LOGGER.error(``"Return value orderResponse object is empty"` `); ` `} ` `map.put(``"result"` ` - ` `1` `); ` `map.put(``"msg"` `, ` `"Abnormal payment environment, please try again later"` `); ` `return` `map; ` `} ` `} ` ` `}Copy the code

The JSP code


`<script type=``"text/javascript"` ` > ` `// Click the pay button to start paying

`function` `toPay(){`

`// Preliminary judgment data '

`var` `openId=$(``"#openId"``).val(); ` `var` `payMoney=$(``"#payMoney"``).val(); ` `$.ajax({` `url :` `"${pageContext.request.contextPath}/toPayInit"``,`

`type:``"POST"``,`

`dataType :` `'json'``,`

`data:{`

`payMoney:payMoney,`

`openId:openId,`

`orderId:``"Order Number"`

`},`

`success :` `function``(result) {`

`if``(result.result==1){` `var` `paySign = result.paySign; ` `var` `prepay_id = result.prepay_id; ` `var` `nonceStr = result.noncestr; ` `var` `timestamp = result.timestamp; ` `var` `unifiedOrderRequest = result.unifiedOrderRequest; ` `var` `spbill_create_ip = unifiedOrderRequest.spbill_create_ip; ` `var` `detail = unifiedOrderRequest.detail; ` `var` `out_trade_no = unifiedOrderRequest.out_trade_no; ` `var` `appId=result.appId; ` `onBridgeReady(paySign,prepay_id,nonceStr,timestamp,appId); ` `} ` `else``{`

`alert(``"Failure"` `); ` `}` `},` `error :` `function``(data, status, e) {` `// The server response fails

`alert(``"Data abnormal, payment failed"` `, ` `'error'` `); ` `} ` `}); ` `} ` `// call the public account to pay '

`function` `onBridgeReady(paySign,prepay_id,nonceStr,timestamp,appId){`

`WeixinJSBridge.invoke(`

`'getBrandWCPayRequest'` `, {` `"appId"``:appId,` `//appid`

`"timeStamp"``:timestamp,`

`"nonceStr"``:nonceStr,` `// random string '

`"package"` ` : ` `"prepay_id="``+prepay_id,`

`"signType"` ` : ` `"MD5"` `, ` `"paySign"``:paySign` `// Wechat signature '

`},`

`function``(res){`

`// Using the above method to judge the front-end return, the wechat team solemnly reminds: res.err_msg will return OK after the user pays successfully, but it does not guarantee that it is absolutely reliable. `

`if``(res.err_msg ==` `"get_brand_wcpay_request:ok"` `) {`

`alert(``"Payment completed"` `, ` `'success'` `); ` `} ` `else` `if``(res.err_msg ==` `"get_brand_wcpay_request:cancel"` `) {`

`alert(``"Cancel payment"` `, ` `'success'` `); ` `} ` `else` `if``(res.err_msg ==` `"get_brand_wcpay_request:fail"``){`

`alert(``"Payment failure"` `, ` `'success'` `); ` `} ` `} ` `); ` `}` `</script>`Copy the code

Define the wechat payment success callback interface apiauPostController.java

`package` `com.yiexpress.api.controller.ewe.aupost; ` `import` `java.util.HashMap; ` `import` `java.util.Map; ` `import` `javax.annotation.Resource; ` `import` `javax.servlet.ServletInputStream; ` `import` `javax.servlet.http.HttpServletRequest; ` `import` `javax.servlet.http.HttpServletResponse; ` `import` `org.apache.commons.collections.MapUtils; ` `import` `org.slf4j.Logger; ` `import` `org.slf4j.LoggerFactory; ` `import` `org.springframework.beans.factory.annotation.Value; ` `import` `org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; ` `import` `org.springframework.stereotype.Controller; ` `import` `org.springframework.web.bind.annotation.RequestMapping; ` `import` `org.springframework.web.bind.annotation.ResponseBody; ` `import` `com.yiexpress.core.utils.wechat.WXPayUtil; ` `@Controller` `@RequestMapping``(``"/api"` `) ` `public` `class` `APIAupostController {`

`private` `static` `final` `Logger LOGGER=LoggerFactory.getLogger(APIAupostController.``class``); ` `@Resource``(name =` `"jacksonBean"` `) ` `private` `MappingJackson2HttpMessageConverter jackson; ` `private` `String apiKey=``"Merchant Key"` `; ` `// Merchant key '

`/** * asynchronous callback interface ' '* @param Request' '* @param Response' '* @throws Exception' '*/`

`@RequestMapping``(value=``"/paymentNotice"``,produces=``"text/html; charset=utf-8"``)`

`@ResponseBody`

`public` `String WeixinParentNotifyPage(HttpServletRequest request,HttpServletResponse response)` `throws` `Exception{` `ServletInputStream instream = request.getInputStream(); ` `StringBuffer sb =` `new` `StringBuffer(); ` `int` `len = -``1` `; ` `byte``[] buffer =` `new` `byte``[``1024` `]; ` `while``((len = instream.read(buffer)) ! = - ` `1``){`

`sb.append(``new` `String(buffer,``0``,len)); ` `}` `instream.close(); ` `Map<String,String>map= WXPayUtil.xmlToMap(sb.toString()); ` `// Accept notification parameter 'for wechat callback

`Map<String,String> return_data =` `new` `HashMap<String,String>(); ` `// Check whether the signature is correct

`if``(WXPayUtil.isSignatureValid(map,apiKey)){`

`if` ` (map.get(``"return_code"``).toString().equals(``"FAIL"``)){`

`return_data.put(``"return_code"` `, ` `"FAIL"` `); ` `return_data.put(``"return_msg"` `,map.get(``"return_msg"` `)); ` `} ` `else` `{`

`String return_code=MapUtils.getString(map, ` `"return_code"` `); ` `String result_code=MapUtils.getString(map, ` `"result_code"` `); ` `if``(return_code! =``null` `&&` `"SUCCESS"``.equals(return_code) && result_code! =``null` `&&` `"SUCCESS"``.equals(result_code)){`

`String out_trade_no =MapUtils.getString(map, ` `"out_trade_no"` `); ` `// System order number '

`// The payment is successful, you can customize the new logic '`} ` `} ` `} ` `else``{`

`return_data.put(``"return_code"` `, ` `"FAIL"` `); ` `return_data.put(``"return_msg"` `, ` `"Signature error"` `); ` `}` `String xml = WXPayUtil.GetMapToXML(return_data); ` `LOGGER.error(``"Payment notification callback result:"``+xml); ` `return` `xml; ` ` `} ` `}Copy the code

The above is all the content of this article, I hope to help you learn.