微信支付之統一下單
阿新 • • 發佈:2019-01-07
打包簽名檔案debug:
app-build-outputs-apk-debug.apk
Map集合轉xml串:
List集合轉xml串:Map<String, String> params = new HashMap<>(); params.put("appid", APP_ID); params.put("mch_id", MCH_ID); params.put("nonce_str", randomNum); params.put("sign", sign); params.put("body", BODY); StringBuffer sb = new StringBuffer(); // sb.append("<xml>\n"); Set es = params.entrySet(); Iterator iterator = es.iterator(); while (iterator.hasNext()) { Map.Entry entry = (Map.Entry) iterator.next(); String k = (String) entry.getKey(); String v = (String) entry.getValue(); sb.append("<" + k + ">" + v + "</" + k + ">\n"); }
由xml串得map集合:List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); list.add(new BasicNameValuePair("appid", APP_ID)); list.add(new BasicNameValuePair("mch_id", MCH_ID)); list.add(new BasicNameValuePair("nonce_str", randomNum)); list.add(new BasicNameValuePair("sign", sign)); list.add(new BasicNameValuePair("body", BODY)); StringBuffer buffer = new StringBuffer(); for (int i = 0;i<list.size();i++){ BasicNameValuePair pair = list.get(i); String name = pair.getName(); String value = pair.getValue(); buffer.append("<" + name + ">" + value + "</" + name + ">\n"); }
上面需要用到這個知識點-將一個字串轉化成輸入流:(建一個Util類)public static Map<String, Object> getMapFromXML(String xmlString) throws ParserConfigurationException, IOException, SAXException { //這裡用Dom的方式解析回包的最主要目的是防止API新增回包欄位 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputStream is = Util.getStringStream(xmlString); Document document = builder.parse(is); //獲取到document裡面的全部結點 NodeList allNodes = document.getFirstChild().getChildNodes(); Node node; Map<String, Object> map = new HashMap<String, Object>(); int i = 0; while (i < allNodes.getLength()) { node = allNodes.item(i); if (node instanceof Element) { map.put(node.getNodeName(), node.getTextContent()); } i++; } return map; }
public class Util {
public static InputStream getStringStream(String sInputString) {
if (sInputString != null && !sInputString.trim().equals("")) {
try {
ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes());
return tInputStringStream;
} catch (Exception ex) {
ex.printStackTrace();
}
}
return null;
}
}
生成32位隨機數:String randomNum = getRandomStringByLength(32);
Log.i(TAG, "order: 隨機數"+randomNum);
private static String getRandomStringByLength(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
okhttp請求:
Request request = new Request.Builder().url("https://api.mch.weixin.qq.com/pay/unifiedorder").post(RequestBody.create(MediaType.parse("text/xml"), sb.toString())).build();
把RequestBody用create生成
httpClient請求:
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
httpPost.setEntity(entity);
改為如下程式碼錯誤:
// StringEntity entity = new StringEntity(buffer.toString(), "text/xml");
// httpPost.setEntity(entity);
最後用HttpConnection-getOutputStream傳送請求-getInputStream響應資料
遍歷map集合資料:
Iterator it = maps.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
Object value = entry.getValue();
Log.i(TAG, "order: key==="+key+"----"+"value==="+value);
}
map集合包含key值map.contains(key) map集合get某個key對應的值map.get("key")httpConnection-post請求:
String xmlData = getXmlData();
URL url = new URL("https://api.mch.weixin.qq.com/pay/unifiedorder");
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
//傳送請求
PrintWriter out = new PrintWriter(httpConn.getOutputStream());
out.print(xmlData.toString());//在此處傳入xml串
out.flush();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
//獲取響應
BufferedInputStream bufferedInputStream = new BufferedInputStream(httpConn.getInputStream());
byte[] buf = new byte[1024];
StringBuilder builder = new StringBuilder();
int read = 0;
while ((read = bufferedInputStream.read(buf)) >= 0) {
builder.append(new String(buf, 0, read));
}
String result = builder.toString();
Log.i(TAG, "xml結果為:" + result);
//判斷返回資料
Map<String, Object> maps = getMapFromXML(result);
String return_code = (String) maps.get("return_code");
String return_msg = (String) maps.get("return_msg");
String result_code = (String) maps.get("result_code");
if (return_code.equals("SUCCESS") && result_code.equals("SUCCESS")) {
Log.i(TAG, "order: " + "交易成功");
String trade_type = (String) maps.get("trade_type");
String prepay_id = (String) maps.get("prepay_id");
Log.i(TAG, "order: 第一步返回結果為:" + "trade_type===" + trade_type + " prepay_id===" + prepay_id);
} else if (return_code.equals("FAIL")) {
Log.i(TAG, "order: " + "交易失敗");
}
}
md5加密:package com.ddgl.ddlx;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Md5 {
private final static String[] strDigits = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
// 返回形式為數字跟字串
private static String byteToArrayString(byte bByte) {
int iRet = bByte;
// System.out.println("iRet="+iRet);
if (iRet < 0) {
iRet += 256;
}
int iD1 = iRet / 16;
int iD2 = iRet % 16;
return strDigits[iD1] + strDigits[iD2];
}
// 返回形式只為數字
private static String byteToNum(byte bByte) {
int iRet = bByte;
System.out.println("iRet1=" + iRet);
if (iRet < 0) {
iRet += 256;
}
return String.valueOf(iRet);
}
// 轉換位元組陣列為16進位制字串
private static String byteToString(byte[] bByte) {
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < bByte.length; i++) {
sBuffer.append(byteToArrayString(bByte[i]));
}
return sBuffer.toString();
}
public final static String md5(String str) {
String resultString = null;
try {
resultString = new String(str);
MessageDigest md = MessageDigest.getInstance("MD5");
// md.digest() 該函式返回值為存放雜湊值結果的byte陣列
resultString = byteToString(md.digest(str.getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return resultString;
}
}