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

微信原生支付“模式二”实现

2015-11-27 20:09 357 查看
可以解决跨号支付的问题,废话不多说,相信大家都知道模式二的一些基本知识逻辑,下面我就直接上自己写的代码。

request.setCharacterEncoding("utf-8");
boolean hasError = false;
JSONObject messageJSAPI = new JSONObject();
ApplicationContext ctx =
WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());

OrderService orderService = (OrderService) ctx.getBean("orderTableService");

String out_trade_no = request.getParameter("orderNumber");
String product_id = request.getParameter("activityId");
JSONObject orderJSON = orderService.getOrderPayInfo(out_trade_no);

String openId = (String) request.getSession().getAttribute("openId");

//付款金额
double total_fee = orderJSON.getDouble("orderTotalPrice");

//商品订单号
String order_number = orderJSON.getString("orderNumber");
//商品ID
String order_activityId = new String(orderJSON.getString("activityId"));

//订单说明
String order_activityName = new String(orderJSON.getString("orderActivityName"));
int total_fee1 = (new Double(total_fee*100)).intValue();

TreeMap<String, String> paramMap = new TreeMap<String,String>();
paramMap.put("appid", "");//appid
paramMap.put("body", order_activityName);    //描述order_activityName
paramMap.put("mch_id","");//商户号
paramMap.put("nonce_str", getRandomString(16)); //随机数
paramMap.put("notify_url", ""); //支付成功后,回调地址
paramMap.put("out_trade_no", order_number);  //商户 后台的贸易单号 order_number
paramMap.put("product_id",order_activityId);
paramMap.put("spbill_create_ip",""); // 商户根据自己业务传递的参数 必填
paramMap.put("total_fee",""+(new Double(total_fee*100)).intValue()); //金额必须为整数  单位为分
paramMap.put("trade_type", "NATIVE"); //交易类型

StringBuilder sb = new StringBuilder();
for(String key:paramMap.keySet()){
if(paramMap.get(key) != null || "".equals(paramMap.get(key))){
sb.append(key).append("=").append(paramMap.get(key)).append("&");
}
}
sb.append("key=943ed3bd1e3f5799a5ae4d36202dd46a");
System.out.println(sb.toString());
String sign = PasswordUtil.MD5Encode(sb.toString(),"utf-8").toUpperCase();
//String sign = PasswordUtil.md5(sb.toString()).toUpperCase();
paramMap.put("sign",sign);

String xmlData = mapToXML(paramMap);//把参数转换成XML数据格式

String resXml = HttpRequest.sendPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xmlData);

System.out.println("======"+resXml);

Document dd = null;
String code_url = null;
try{
dd = DocumentHelper.parseText(resXml);
}catch(DocumentException e){
e.printStackTrace();
}
if(dd != null){
Element root = dd.getRootElement();
if(root == null){
return ;
}
Element codeUrl = root.element("code_url");
if(codeUrl == null){
System.out.println("codeUrl=null");
}
code_url = codeUrl.getText();//解析xml获得code_url;
}

System.out.println(code_url);
上面的代码是获取订单号等一些参数,下面则是一些格式转换

public String generateSign(String s){
String sign = "";
SAXReader reader = new SAXReader();
ArrayList<String> list = new ArrayList<String>();
try {
Document document = reader.read(new ByteArrayInputStream(s.getBytes("utf-8")));
Element root = document.getRootElement();
List<Element> elementList = root.elements();
for (Element e : elementList){
if(e.getText()!=""&&e.getName()!="sign")
list.add(e.getName() + "=" + e.getText());
}
Collections.sort(list);
StringBuffer string1 = new StringBuffer();
for(int i = 0; i< list.size(); i++){
if(i!=0)
string1.append("&");
string1.append(list.get(i));
}
String plainText = string1+"&key=943ed3bd1e3f5799a5ae4d36202dd46a";
sign = md5(plainText).toUpperCase();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return sign;
}

public static String getRandomString(int length) { //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();
}

public String md5(String plainText) {

String md5Str = null;
try {
StringBuffer buf = new StringBuffer();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes("utf-8"));
byte b[] = md.digest();
int i;

for (int offset = 0; offset < b.length; offset++) {

i = b[offset];
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
md5Str = buf.toString();
} catch (Exception e) {
e.printStackTrace();
}
return md5Str;
}

public static String mapToXML(Map map) {
StringBuffer sb = new StringBuffer();
sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><bizdata>");
mapToXMLTest2(map, sb);
sb.append("</bizdata>");
try {
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

private static void mapToXMLTest2(Map map, StringBuffer sb) {
Set set = map.keySet();
for (Iterator it = set.iterator(); it.hasNext();) {
String key = (String) it.next();
Object value = map.get(key);
if (null == value)
value = "";
if (value.getClass().getName().equals("java.util.ArrayList")) {
ArrayList list = (ArrayList) map.get(key);
sb.append("<" + key + ">");
for (int i = 0; i < list.size(); i++) {
HashMap hm = (HashMap) list.get(i);
mapToXMLTest2(hm, sb);
}
sb.append("</" + key + ">");

} else {
if (value instanceof HashMap) {
sb.append("<" + key + ">");
mapToXMLTest2((HashMap) value, sb);
sb.append("</" + key + ">");
} else {
sb.append("<" + key + ">" + value + "</" + key + ">");
}

}

}
}


下面的代码是有关页面的

<body>
<div data-role="page" id="home">
<div data-role="header" data-position="fixed">
<h1>微信支付</h1>
</div>
<ul id="desc">
<li><a href="#" style="color:blue;" >1.请长按二维码后,点击「识别图中二维码」</a></li>
<li><a href="#" style="color:blue;" >2.支付成功后,可在我的票务中查看票务信息</a></li>
</ul>
<div id="qrcode" title=code_url style="TEXT-ALIGN: center;">

</div>
</body>

<script src="anotherqrcode.js"></script>
<script>
(function() {
new QRCode('qrcode', {
text: '<%=code_url%>' ,
width:  180,
height: 180,
margin: 15,
colorDark: '#000',
colorLight: '#fff',
correctLevel: QRCode.CorrectLevel.L
});
})();
</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: