微信支付

使用微信支付时需要将app注册到微信

api = WXAPIFactory.createWXAPI(this, "appid");
api.registerApp("appid");//注册到微信

服务端访问微信接口生成订单信息
签名生成步骤:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=4_3
sign的生成方法如下:

//定义签名,微信根据参数字段的ASCII码值进行排序 加密签名,故使用SortMap进行参数排序
public static String createSign(String characterEncoding, SortedMap 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;}

请求参数里还需要生成随机订单号:

/** * 生成随机订单号。
 * * @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参数要转换成xml样式的String类型参数以便上传

SortedMap 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");//总金额,参数支付金额单位为【分】,参数值不能带小数
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");//接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
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这六个参数进行二次签名,生成新的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+"";//时间戳,十位数                   
 String str = response.body().string();                   
 Map 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 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();              
  }           
 }       
 });

你可能感兴趣的:(微信支付)