WeChat public account payment (2): unified order, public order

Source: Internet
Author: User

Payment by Public Account (2): uniform order, public order

The user's OpenId has been obtained in the previous article.

This article mainly calls the unified order API of public payment

API address: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php? Chapter = 9_1

The main process is to encapsulate about 20 parameters into the interface address sent to in XML format, and then you can get the returned content, if the payment is successful, the pre-payment ID is required.

The request parameters are not explained.

Here, the random string: I use UUID to strip

1 public static String create_nonce_str() {2       return UUID.randomUUID().toString().replace("-","");3 }

Merchant Order Number: Each order number can only be used once, so the timestamp of the system order number is used.

Total amount: cannot be 0

Notification address: the address that the system calls back if the payment is successful or fails.

Signature:

1 import java. io. serializable; 2 3 public class PayInfo implements Serializable {4 5 private static final long serialVersionUID = 5637164279924222380L; 6 private String appid; 7 private String mch_id; 8 private String device_info; 9 private String nonce_str; 10 private String sign; 11 private String body; 12 private String attach; 13 private String out_trade_no; 14 private int total_timeout; 15 private String spbill_create_ip; 16 private String policy_url; 17 private String trade_type; 18 private String openid; 19 20 // The following is get, set Method 21}
1/** 2 * create a uniform xml java object for the Order 3 * @ param bizOrder system business order number 4 * @ param ip user's ip address 5 * @ param openId user's openId 6 * @ return 7 */8 public PayInfo createPayInfo (BizOrder bizOrder, string ip, String openId) {9 PayInfo payInfo = new PayInfo (); 10 payInfo. setAppid (Constants. appid); 11 payInfo. setDevice_info ("WEB"); 12 payInfo. setMch_id (Constants. mch_id); 13 payInfo. setNonce_str (CommonUtil. create_nonce_str (). replace ("-", ""); 14 payInfo. setBody ("here is the body of a certain white rice"); 15 payInfo. setAttach (bizOrder. getId (); 16 payInfo. setOut_trade_no (bizOrder. getOrderCode (). concat (""). concat (DateFormatUtils. format (new Date (), "MMddHHmmss"); 17 payInfo. setTotal_fee (int) bizOrder. getFeeAmount (); 18 payInfo. setSpbill_create_ip (ip); 19 payInfo. setpolicy_url (Constants. notify_url); 20 payInfo. setTrade_type ("JSAPI"); 21 payInfo. setOpenid (openId); 22 return payInfo; 23}

Obtain the signature:

1/** 2 * get the signature 3 * @ param payInfo 4 * @ return 5 * @ throws Exception 6 */7 public String getSign (PayInfo payInfo) throws Exception {8 String signTemp = "appid =" + payInfo. getAppid () 9 + "& attach =" + payInfo. getAttach () 10 + "& body =" + payInfo. getBody () 11 + "& device_info =" + payInfo. getDevice_info () 12 + "& mch_id =" + payInfo. getMch_id () 13 + "& nonce_str =" + payInfo. getNonce_str () 14 + "& policy_url =" + payInfo. getpolicy_url () 15 + "& openid =" + payInfo. getOpenid () 16 + "& out_trade_no =" + payInfo. getOut_trade_no () 17 + "& spbill_create_ip =" + payInfo. getSpbill_create_ip () 18 + "& total_fee =" + payInfo. getTotal_fee () 19 + "& trade_type =" + payInfo. getTrade_type () 20 + "& key =" + Constants. key; // This key must be 21 22 MessageDigest md5 = MessageDigest. getInstance ("MD5"); 23 md5.reset (); 24 md5.update (signTemp. getBytes ("UTF-8"); 25 String sign = CommonUtil. byteToStr (md5.digest ()). toUpperCase (); 26 return sign; 27}

Note: The preceding Constants. key value is in the API key of the merchant id api security.

Some tool Methods: get the IP address, convert the byte array to a hexadecimal string, and convert the byte to a hexadecimal string.

1/** 2 * convert the byte array to a hexadecimal String 3*4 * @ param byteArray 5 * @ return 6 */7 public static String byteToStr (byte [] byteArray) {8 String strDigest = ""; 9 for (int I = 0; I <byteArray. length; I ++) {10 strDigest + = byteToHexStr (byteArray [I]); 11} 12 return strDigest; 13} 14 15/** 16 * convert byte to hexadecimal String 17*18 * @ param btyes19 * @ return20 */21 public static String byteToHexStr (byte bytes) {22 char [] Digit = {'0', '1', '2', '3', '4', '5', '6', '7 ', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F '}; 23 char [] tempArr = new char [2]; 24 tempArr [0] = Digit [(bytes >>> 4) & 0X0F]; 25 tempArr [1] = Digit [bytes & 0X0F]; 26 27 String s = new String (tempArr); 28 return s; 29} 30 31/** 32 * Get IP address 33 * @ param request34 * @ return35 */36 public static String getIpAddr (HttpServletRequest request) {37 InetAddress addr = null; 38 try {39 addr = InetAddress. getLocalHost (); 40} catch (UnknownHostException e) {41 return request. getRemoteAddr (); 42} 43 byte [] ipAddr = addr. getAddress (); 44 String ipAddrStr = ""; 45 for (int I = 0; I <ipAddr. length; I ++) {46 if (I> 0) {47 ipAddrStr + = ". "; 48} 49 ipAddrStr + = ipAddr [I] & 0xFF; 50} 51 return ipAddrStr; 52}

In this way, the signature is obtained, and other data in the signature and PayInfo are converted into XML format and passed as parameters to the unified order address.

1 PayInfo pi = pu.createPayInfo(bo,"10.204.3.32","22");2 String sign = pu.getSign(pi);3 pi.setSign(sign);

Object To XML

1/** 2 * extend xstream to support CDATA 3 */4 private static XStream xstream = new XStream (new XppDriver () {5 public HierarchicalStreamWriter createWriter (Writer out) {6 return new PrettyPrintWriter (out) {7 // Add the CDATA flag 8 boolean cdata = true; 9 10 @ SuppressWarnings ("rawtypes") 11 public void startNode (String name, class clazz) {12 super. startNode (name, clazz); 13} 14 15 protected void writeText (QuickWriter Writer, String text) {16 if (cdata) {17 writer. write ("<! [CDATA ["); 18 writer. write (text); 19 writer. write ("]>"); 20} else {21 writer. write (text); 22} 23} 24}; 25} 26}); 27 28 public static String payInfoToXML (PayInfo pi) {29 xstream. alias ("xml", pi. getClass (); 30 return xstream. toXML (pi); 31}

Xml to Map

 1     @SuppressWarnings("unchecked") 2     public static Map<String, String> parseXml(String xml) throws Exception { 3         Map<String, String> map = new HashMap<String, String>(); 4  5         Document document = DocumentHelper.parseText(xml); 6         Element root = document.getRootElement(); 7         List<Element> elementList = root.elements(); 8  9         for (Element e : elementList)10             map.put(e.getName(), e.getText());11         return map;12     }    

The following is the URL of the unified order.

1   log.info(MessageUtil.payInfoToXML(pi).replace("__", "_"));2   Map<String, String> map = CommonUtil.httpsRequestToXML("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", MessageUtil.payInfoToXML(pi).replace("__", "_").replace("<![CDATA[", "").replace("]]>", ""));3    log.info(map);
1 public static Map <String, String> httpsRequestToXML (String requestUrl, String requestMethod, String outputStr) {2 Map <String, String> result = new HashMap <> (); 3 try {4 StringBuffer buffer = httpsRequest (requestUrl, requestMethod, outputStr); 5 result = MessageUtil. parseXml (buffer. toString (); 6} catch (ConnectException ce) {7 log. error ("connection Timeout:" + ce. getMessage (); 8} catch (Exception e) {9 log. error ("https request exception:" + ece. getMessage (); 10} 11 return result; 12}
HttpsRequest () method in the first article
If the Map obtained above is successful, there will be
1 String return_code = map. get ("return_code"); 2 if (StringUtils. isNotBlank (return_code) & return_code.equals ("SUCCESS") {3 String return_msg = map. get ("return_msg"); 4 if (StringUtils. isNotBlank (return_msg )&&! Return_msg.equals ("OK") {5 return "unified order Error! "; 6} 7} else {8 return" unified order Error! "; 9} 10 11 String prepay_Id = map. get (" prepay_id ");

This prepay_id is the pre-payment ID. It is required for later payment.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.