微信"號付出(二)完成同一下單接口。本站提示廣大學習愛好者:(微信"號付出(二)完成同一下單接口)文章只能為提供參考,不一定能成為您想要的結果。以下是微信"號付出(二)完成同一下單接口正文
上一篇曾經獲得到了用戶的OpenId
這篇重要是挪用微信"付出的同一下單API
API地址:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
看文檔,重要流程就是把20個閣下的參數封裝為XML格局發送到微信給的接口地址,然後便可以獲得到前往的內容了,假如勝利外面就有付出所須要的預付付ID
要求參數就不說明了。
個中,隨機字符串:我用的是UUID去中劃線
public static String create_nonce_str() {
return UUID.randomUUID().toString().replace("-","");
}
商戶定單號:每一個定單號只能應用一次,所以用的是體系的定單號加的時光戳。
總金額:不克不及為
告訴地址:微信付出勝利或掉敗回調給體系的地址
簽名:
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 notify_url;
private String trade_type;
private String openid;
//上面是get,set辦法
}
/**
* 創立同一下單的xml的java對象
* @param bizOrder 體系中的營業單號
* @param ip 用戶的ip地址
* @param openId 用戶的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("這裡是某某白米飯的body");
payInfo.setAttach(bizOrder.getId());
payInfo.setOut_trade_no(bizOrder.getOrderCode().concat("A").concat(DateFormatUtils.format(new Date(), "MMddHHmmss")));
payInfo.setTotal_fee((int)bizOrder.getFeeAmount());
payInfo.setSpbill_create_ip(ip);
payInfo.setNotify_url(Constants.notify_url);
payInfo.setTrade_type("JSAPI");
payInfo.setOpenid(openId);
return payInfo;
}
獲得簽名:
/**
* 獲得簽名
* @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()
+"¬ify_url="+payInfo.getNotify_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; //這個key留意
MessageDigest md = MessageDigest.getInstance("MD");
md.reset();
md.update(signTemp.getBytes("UTF-"));
String sign = CommonUtil.byteToStr(md.digest()).toUpperCase();
return sign;
}
留意:下面的Constants.key取值在商戶號API平安的API密鑰中。
一些對象辦法:獲得ip地址,將字節數組轉換為十六進制字符串,將字節轉換為十六進制字符串
/**
* 將字節數組轉換為十六進制字符串
*
* @param byteArray
* @return
*/
public static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = ; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 將字節轉換為十六進制字符串
*
* @param btyes
* @return
*/
public static String byteToHexStr(byte bytes) {
char[] Digit = { '', '', '', '', '', '', '', '', '', '', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[];
tempArr[] = Digit[(bytes >>> ) & XF];
tempArr[] = Digit[bytes & XF];
String s = new String(tempArr);
return s;
}
/**
* 獲得ip地址
* @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;
}
如許就獲得了簽名,把簽名與PayInfo中的其他數據轉成XML格局,當作參數傳遞給同一下單地址。
PayInfo pi = pu.createPayInfo(bo,"...",""); String sign = pu.getSign(pi); pi.setSign(sign);
對象轉XML
/**
* 擴大xstream使其支撐CDATA
*/
private static XStream xstream = new XStream(new XppDriver() {
public HierarchicalStreamWriter createWriter(Writer out) {
return new PrettyPrintWriter(out) {
//增長CDATA標志
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("<![CDATA[");
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轉Map
@SuppressWarnings("unchecked")
public static Map<String, String> parseXml(String xml) throws Exception {
Map<String, String> map = new HashMap<String, String>();
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
List<Element> elementList = root.elements();
for (Element e : elementList)
map.put(e.getName(), e.getText());
return map;
}
上面就是挪用同一下單的URL了
log.info(MessageUtil.payInfoToXML(pi).replace("__", "_"));
Map<String, String> map = CommonUtil.httpsRequestToXML("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", MessageUtil.payInfoToXML(pi).replace("__", "_").replace("<![CDATA[", "").replace("]]>", ""));
log.info(map);
public static Map<String, String> httpsRequestToXML(String requestUrl, String requestMethod, String outputStr) {
Map<String, String> result = new HashMap<>();
try {
StringBuffer buffer = httpsRequest(requestUrl, requestMethod, outputStr);
result = MessageUtil.parseXml(buffer.toString());
} catch (ConnectException ce) {
log.error("銜接超時:"+ce.getMessage());
} catch (Exception e) {
log.error("https要求異常:"+ece.getMessage());
}
return result;
}
httpsRequest()這個辦法在第一篇中
下面獲得到的Map假如勝利的話,外面就會有
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 "同一下單毛病!";
}
}else{
return "同一下單毛病!";
}
String prepay_Id = map.get("prepay_id");
這個prepay_id就是預付付的ID。前面付出須要它。