使用微信支付時需要將app注冊到微信
api = WXAPIFactory.createWXAPI(this, "appid");
api.registerApp("appid");//注冊到微信
服務(wù)端訪問微信接口生成訂單信息
簽名生成步驟:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=4_3
sign的生成方法如下:
//定義簽名耳舅,微信根據(jù)參數(shù)字段的ASCII碼值進行排序 加密簽名,故使用SortMap進行參數(shù)排序
public static String createSign(String characterEncoding, SortedMap<String, String> parameters) {
StringBuffer sb = new StringBuffer();
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
Object v = entry.getValue();
if (null != v && !"".equals(v)
&& !"sign".equals(k) && !"key".equals(k)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + "商戶密鑰");//最后加密時添加商戶密鑰贷岸,由于key值放在最后铐伴,所以不用添加到SortMap里面去世舰,單獨處理贮聂,編碼方式采用UTF-8
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;}
請求參數(shù)里還需要生成隨機訂單號:
/** * 生成隨機訂單號稠腊。
* * @return
*/
private static String getOutTradeNo() {
SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
Date date = new Date();
String key = format.format(date);
Random r = new Random();
key = key + r.nextInt();
key = key.substring(0, 15);
return key;
}
map參數(shù)要轉(zhuǎn)換成xml樣式的String類型參數(shù)以便上傳
SortedMap<String, String> map = new TreeMap<>();
map.put("appid", "wx84b3eaa39d8ed662");
map.put("mch_id", "1415958602");//微信支付分配的商戶號
map.put("nonce_str", (Math.random() * 100000000) + "");//隨機字符串篓跛,不長于32位
map.put("body", "嘉和-測試商品");//商品描述
map.put("out_trade_no", getOutTradeNo());//商戶訂單號
map.put("fee_type", "CNY");//貨幣類型子眶,人民幣為CNY
map.put("total_fee", "1");//總金額瀑凝,參數(shù)支付金額單位為【分】,參數(shù)值不能帶小數(shù)
map.put("spbill_create_ip", "123.124.21.34");//終端IP
map.put("notify_url", "http://wxpay.weixin.qq.com/pub_v2/pay/notify.v2.php");//接收微信支付異步通知回調(diào)地址臭杰,通知url必須為直接可訪問的url粤咪,不能攜帶參數(shù)。
map.put("trade_type", "APP");//支付類型
String sign = createSign("UTF-8", map);map.put("sign", sign);
String xml = XmlUtils.map2xmlBody(map, "XML");
請求微信接口渴杆,返回訂單信息射窒;
返回訂單信息后需要對appid,partnerid将塑,noncestr脉顿,prepayid,prepay_id点寥,timestamp艾疟,package這六個參數(shù)進行二次簽名,生成新的sign敢辩,方法同上
OkHttpClient client = new OkHttpClient.Builder().build();
final Request request = new Request.Builder().url("https://api.mch.weixin.qq.com/pay/unifiedorder")
.post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), xml)).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("", e.getMessage());
}
@Override
public void onResponse(Call call, Response response) {
try {
Date date = new Date(System.currentTimeMillis());
String time=date.getTime()/1000+"";//時間戳蔽莱,十位數(shù)
String str = response.body().string();
Map<String, String> map = XmlUtils.xmlBody2map(str, "xml");
PayReq req = new PayReq();
req.appId = map.get("appid"); // 測試用appId
req.partnerId = map.get("mch_id");
req.prepayId = map.get("prepay_id");
req.nonceStr = map.get("nonce_str");
req.timeStamp = time;
req.packageValue = "Sign=WXPay";
SortedMap<String, String> m = new TreeMap<>();
m.put("appid", "wx84b3eaa39d8ed662");
m.put("partnerid", "1415958602");//微信支付分配的商戶號
m.put("noncestr",map.get("nonce_str"));//隨機字符串,不長于32位
m.put("prepayid", map.get("prepay_id"));//
m.put("timestamp",time);//
m.put("package", "Sign=WXPay");//
req.sign = createSign("UTF-8",m);//
req.extData = "app data"; // optional
api.sendReq(req);
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} finally {
response.body().close();
}
}
});