您的位置:首页 > 移动开发 > 微信开发

微信支付之统一下单

2016-12-03 18:59 239 查看
打包签名文件debug:

app-build-outputs-apk-debug.apk

Map集合转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");
}
List集合转xml串:
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");
}
由xml串得map集合:
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;
}
上面需要用到这个知识点-将一个字符串转化成输入流:(建一个Util类)
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;
}
}

Android, sending XML via HTTP POST (SOAP)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: