This article mainly introduces how to call the unified order API of public payment. you can obtain the returned content by encapsulating parameters in xml format and sending them to the interface address, you can refer to the previous article to obtain the user's OpenId.
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
public static String create_nonce_str() {return UUID.randomUUID().toString().replace("-","");}
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
Notification address: the address that the system calls back if the payment is successful or fails.
Signature:
Import java. io. serializable; public class PayInfo implements Serializable {private static final long serialVersionUID = L; private String appid; private String mch_id; private String device_info; private String nonce_str; private String sign; private String body; private String attach; private String out_trade_no; private int total_fee; private String spbill_create_ip; private String policy_url; private String trade_type; private String openid; // The following is get, set Method}/*** create a uniform xml java object * @ param bizOrder system business order number * @ param ip address user's ip address * @ param openId user's openId * @ return */public PayInfo createPayInfo (BizOrder bizOrder, string ip, String openId) {PayInfo payInfo = new PayInfo (); payInfo. setAppid (Constants. appid); payInfo. setDevice_info ("WEB"); payInfo. setMch_id (Constants. mch_id); payInfo. setNonce_str (CommonUtil. create_nonce_str (). replace ("-", ""); payInfo. setBody ("Here is the body of a certain white rice"); payInfo. setAttach (bizOrder. getId (); payInfo. setOut_trade_no (bizOrder. getOrderCode (). concat (""). concat (DateFormatUtils. format (new Date (), "MMddHHmmss"); payInfo. setTotal_fee (int) bizOrder. getFeeAmount (); payInfo. setSpbill_create_ip (ip); payInfo. setpolicy_url (Constants. notify_url); payInfo. setTrade_type ("JSAPI"); payInfo. setOpenid (openId); return payInfo ;}
Obtain the signature:
/*** Obtain the signature * @ param payInfo * @ return * @ throws Exception */public String getSign (PayInfo payInfo) throws Exception {String signTemp = "appid =" + payInfo. getAppid () + "& attach =" + payInfo. getAttach () + "& body =" + payInfo. getBody () + "& device_info =" + payInfo. getDevice_info () + "& mch_id =" + payInfo. getMch_id () + "& nonce_str =" + payInfo. getNonce_str () + "initialize ify _ url =" + payInfo. getpolicy_url () + "& openid =" + payInfo. getOpenid () + "& out_trade_no =" + payInfo. getOut_trade_no () + "& spbill_create_ip =" + payInfo. getSpbill_create_ip () + "& total_fee =" + payInfo. getTotal_fee () + "& trade_type =" + payInfo. getTrade_type () + "& key =" + Constants. key; // This key must be MessageDigest md = MessageDigest. getInstance ("MD"); md. reset (); md. update (signTemp. getBytes ("UTF-"); String sign = CommonUtil. byteToStr (md. digest ()). toUpperCase (); return sign ;}
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.
/*** Convert a byte array to a hexadecimal String ** @ param byteArray * @ return */public static String byteToStr (byte [] byteArray) {String strDigest = ""; for (int I =; I <byteArray. length; I ++) {strDigest + = byteToHexStr (byteArray [I]);} return strDigest ;} /*** convert bytes to a hexadecimal String ** @ param btyes * @ return */public static String byteToHexStr (byte bytes) {char [] Digit = {'', '', 'B', 'C ', 'D', 'e', 'F'}; char [] tempArr = new char []; tempArr [] = Digit [(bytes >>>) & XF]; tempArr [] = Digit [bytes & XF]; String s = new String (tempArr); return s ;} /*** obtain the IP address * @ param request * @ return */public static String getIpAddr (HttpServletRequest request) {InetAddress addr = null; try {addr = InetAddress. getLocalHost ();} catch (UnknownHostException e) {return request. getRemoteAddr ();} byte [] ipAddr = addr. getAddress (); String ipAddrStr = ""; for (int I =; I <ipAddr. length; I ++) {if (I>) {ipAddrStr + = ". ";}ipaddrstr + = ipAddr [I] & xFF;} return ipAddrStr ;}
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.
PayInfo pi = pu.createPayInfo(bo,"...","");String sign = pu.getSign(pi);pi.setSign(sign);
Object to XML
/*** Extend xstream to support CDATA */private static XStream xstream = new XStream (new XppDriver () {public HierarchicalStreamWriter createWriter (Writer out) {return new PrettyPrintWriter (out) {// add the CDATA flag boolean cdata = true; @ SuppressWarnings ("rawtypes") public void startNode (String name, Class clazz) {super. startNode (name, clazz);} protected void writeText (QuickWriter writer, String text) {if (cdata) {writer. write (""); writer.write(text); writer.write("");} Else {writer. write (text) ;}};}}); public static String payInfoToXML (PayInfo pi) {xstream. alias ("xml", pi. getClass (); return xstream. toXML (pi );}
Xml to Map
@SuppressWarnings("unchecked")public static Map
parseXml(String xml) throws Exception { Map
map = new HashMap
(); Document document = DocumentHelper.parseText(xml); Element root = document.getRootElement(); List
elementList = root.elements(); for (Element e : elementList) map.put(e.getName(), e.getText()); return map;}
The following is the URL of the unified order.
Log.info (MessageUtil. payInfoToXML (pi). replace ("_", "_"); Map
Map = CommonUtil. httpsRequestToXML ("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", MessageUtil. payInfoToXML (pi). replace ("_", "_"). replace ("", "").replace(""," "); Log.info (map); public static Map
HttpsRequestToXML (String requestUrl, String requestMethod, String outputStr) {Map
Result = new HashMap <> (); try {StringBuffer buffer = httpsRequest (requestUrl, requestMethod, outputStr); result = MessageUtil. parseXml (buffer. toString ();} catch (ConnectException ce) {log. error ("connection timeout:" + ce. getMessage ();} catch (Exception e) {log. error ("https request exception:" + ece. getMessage ();} return result ;}
HttpsRequest () method in the first article
If the Map obtained above is successful, there will be
String return_code = map. get ("return_code"); if (StringUtils. isNotBlank (return_code) & return_code.equals ("SUCCESS") {String return_msg = map. get ("return_msg"); if (StringUtils. isNotBlank (return_msg )&&! Return_msg.equals ("OK") {return "unified order error! ";}} Else {return" unified order error! ";} String prepay_Id = map. get (" prepay_id ");
This prepay_id is the pre-payment ID. It is required for later payment.
For more public account payment (2) how to implement unified order interface related articles, please pay attention to PHP Chinese network!