首页 > 上网技巧 > 电脑小技巧 > Java微信APP支付之统一下单

Java微信APP支付之统一下单

时间:2018-09-16 10:18 作者:QQ地带 我要评论

最近因为公司的业务需要,需要自主开发一套类似淘宝、京东的购物APP系统,本人负责后端在线支付模块接口的开发,主要包含微信、支付宝的统一下单、支付结果通知、申请退款、退款结果通知等接口的开发。费话不多说,我们这一章主要讲述微信APP支付的统一下单接口的开发。
 
官方的API地址:https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_1
 
这里我们先讲述一下总体流程
 
商户系统和微信支付系统主要交互说明:
 
步骤1:用户在商户APP中选择商品,提交订单,选择微信支付。
 
步骤2:商户后台收到用户支付单,调用微信支付统一下单接口。参见【统一下单API】。
 
步骤3:统一下单接口返回正常的prepay_id,再按签名规范重新生成签名后,将数据传输给APP。参与签名的字段名为appid,partnerid,prepayid,noncestr,timestamp,package。注意:package的值格式为Sign=WXPay
 
步骤4:商户APP调起微信支付。api参见本章节【app端开发步骤说明】
 
步骤5:商户后台接收支付通知。api参见【支付结果通知API】
 
步骤6:商户后台查询支付结果。api参见【查询订单API】
 
1、应用场景
商户系统先调用该接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易会话标识后再在APP里面调起支付。
 
2、接口链接
URL地址:https://api.mch.weixin.qq.com/pay/unifiedorder
 
3、是否需要证书
不需要
 
4、请求参数
此处列出必要的参数,如需要查看详细参数,请查阅官方API。
 
字段名 变量名 必填 类型 示例值 描述
应用ID appid String(32) wxd678efh567hg6787 微信开放平台审核通过的应用APPID(请登录open.weixin.qq.com查看,注意与公众号的APPID不同)
商户号 mch_id String(32) 1230000109 微信支付分配的商户号
随机字符串 nonce_str String(32) 5K8264ILTKCH16CQ2502SI8ZNMTM67VS 随机字符串,不长于32位。推荐随机数生成算法
签名 sign String(32) C380BEC2BFD727A4B6845133519F3AD6 签名,详见签名生成算法
商品描述 body String(128) 腾讯充值中心-QQ会员充值
商品描述交易字段格式根据不同的应用场景按照以下格式:
 
APP——需传入应用市场上的APP名字-实际商品名称,天天爱消除-游戏充值。
 
商户订单号 out_trade_no String(32) 20150806125346 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*且在同一个商户号下唯一。详见商户订单号
总金额 total_fee Int 888 订单总金额,单位为分,详见支付金额
终端IP spbill_create_ip String(16) 123.12.12.123 用户端实际ip
通知地址 notify_url String(256) http://www.weixin.qq.com/wxpay/pay.php 接收微信支付异步通知回调地址,通知url必须为直接可访问的url,不能携带参数。
交易类型 trade_type String(16) APP 支付类型
 5、代码实现
5.1基础类
WeChatConfig配置类,主要包含微信的配置信息
 
package com.hisap.xql.api.common.wechat;
 
/**
 * @Author: QijieLiu
 * @Description: 微信配置信息
 * @Date: Created in 16:47 2018/8/14
 */
public class WeChatConfig {
public static String APP_ID = "xxxxxx";
public static String MCH_ID = "xxxxxx";
public static String MCH_KEY = "xxxxxx";
public static String APP_SECRET = "xxxxxx";
public static String UNIFIEDORDER_URL = "https://api.mch.weixin.qq.com/pay/unifiedorder";
public static String NOTIFY_URL = "http://xxx.xxx.xxx.xxx:8080/XqlApi/wechatpay/paynotify";
public static String REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
public static String REFUND_NOTIFY_URL = "http://xxx.xxx.xxx.xxx:8080/XqlApi/wechatpay/refundnotify";
public static String TRADE_TYPE = "APP";
public static String CERT_URL="E:\\cert\\apiclient_cert.p12";
}
 ResponseJson基础类,主要与APP前端进行交互
 
package com.hisap.xql.api.common.bean;
 
public class ResponseJson {
// 结果码
private String code;
// 结果说明
private String message;
// 内容
private Object data;
 
public String getCode() {
return code;
}
 
public void setCode(String code) {
this.code = code;
}
 
public String getMessage() {
return message;
}
 
public void setMessage(String message) {
this.message = message;
}
 
public Object getData() {
return data;
}
 
public void setData(Object data) {
this.data = data;
}
 
}
5.2工具类
MD5Utils类
 
package com.hisap.xql.api.common.utils;
 
import java.security.MessageDigest;
 
/**
 * @Author: QijieLiu
 * @Description: MD5加密工具
 * @Date: Created in 09:39 2018/8/17
 */
public class MD5Utils {
 
public final static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
 
private static String byteArrayToHexString(byte b[]) {
StringBuffer resultSb = new StringBuffer();
for (int i = 0; i < b.length; i++)
resultSb.append(byteToHexString(b[i]));
 
return resultSb.toString();
}
 
private static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n += 256;
int d1 = n / 16;
int d2 = n % 16;
return hexDigits[d1] + hexDigits[d2];
}
 
public static String MD5Encode(String origin, String charsetname) {
String resultString = null;
try {
resultString = new String(origin);
MessageDigest md = MessageDigest.getInstance("MD5");
if (charsetname == null || "".equals(charsetname))
resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
else
resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
}
catch (Exception exception) {
}
return resultString;
}
 
private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
 
public static void main(String[] asd) {
String con = "hello kitty";
String str = MD5Encode(con, "UTF-8");
System.out.println(str.toUpperCase());
}
}
DateUtil类
 
package com.hisap.xql.api.common.utils;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class DateUtil {
public static final String DF_STANDARD = "yyyy-MM-dd HH:mm:ss";
public static final String DF_DATE = "yyyy-MM-dd";
 
/**
* 时间戳转换成日期格式字符串
* @param seconds 精确到毫秒的字符串
* @param formatStr
* @return
*/
public static String timeStamp2Date(String miniSeconds, String format) {
if (miniSeconds == null || miniSeconds.isEmpty() || miniSeconds.equals("null")) {
return null;
}
if (format == null || format.isEmpty()) {
format = "yyyy-MM-dd HH:mm:ss";
}
SimpleDateFormat sdf = new SimpleDateFormat(format);
return sdf.format(new Date(Long.valueOf(miniSeconds)));
}
 
/**
* 获取精确到秒的时间戳
* @param date
* @return
*/
public static Integer getSecondTimestamp(Date date) {
if (null == date) {
return 0;
}
String timestamp = String.valueOf(date.getTime() / 1000);
return Integer.valueOf(timestamp);
}
 
/**
* 字符串转时间
* @param date
* @param dateFormat
* @return
*/
public static Date stringToDate(String date, String dateFormat) {
        SimpleDateFormat formatDate = new SimpleDateFormat(dateFormat);
        try {
            return formatDate.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
/**
* 日期转字符串
* @param date
* @param dateFormat
* @return
*/
public static String dateToString(Date date, String dateFormat) {
        SimpleDateFormat formatDate = new SimpleDateFormat(dateFormat);
        return formatDate.format(date);
    }
/**
* 验证时间合法性
* @param date
* @param dateFormat
* @return
*/
public static boolean isValidDateTime(String date, String dateFormat) {
boolean convertSuccess = true;
SimpleDateFormat formatDate = new SimpleDateFormat(dateFormat);
        try {
        // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期,比如2007/02/29会被接受,并转换成2007/03/01
        formatDate.setLenient(false);
            formatDate.parse(date);
        } catch (Exception e) {
        convertSuccess = false;
        }
        return convertSuccess;
}
/**
* 获取几天前的时间
* @param d
* @param day
* @return
*/
public static Date getDateBefore(Date d, int day) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
return now.getTime();
}
 
/**
* 获取几天后的时间
* @param d
* @param day
* @return
*/
public static Date getDateAfter(Date d, int day) {
Calendar now = Calendar.getInstance();
now.setTime(d);
now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
return now.getTime();
}
}
CommonUtil类
 
package com.hisap.xql.api.common.wechat;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
 
import javax.net.ssl.SSLContext;
 
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
 
import com.hisap.xql.api.common.utils.MD5Utils;
 
/**
 * @Author: QijieLiu
 * @Description: 微信支付工具类
 * @Date: Created in 19:39 2018/8/21
 */
public class CommonUtil {
// 微信参数配置
public static String API_KEY = WeChatConfig.MCH_KEY;
 
// 随机字符串生成
public static String getRandomString(int length) { // length表示生成字符串的长度
String base = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
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();
}
 
// 请求xml组装
public static String getRequestXml(SortedMap<String, Object> parameters) {
StringBuffer sb = new StringBuffer();
sb.append("<xml>");
Set es = parameters.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
String value = entry.getValue().toString();
if ("attach".equalsIgnoreCase(key) || "body".equalsIgnoreCase(key)
|| "sign".equalsIgnoreCase(key)) {
sb.append("<" + key + ">" + "<![CDATA[" + value + "]]></" + key
+ ">");
} else {
sb.append("<" + key + ">" + value + "</" + key + ">");
}
}
sb.append("</xml>");
return sb.toString();
}
 
// 生成签名
public static String createSign(String characterEncoding,
SortedMap<String, Object> 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=" + API_KEY);
System.out.println(sb.toString());
String sign = MD5Utils.MD5Encode(sb.toString(), characterEncoding)
.toUpperCase();
return sign;
}
 
/**
* 验证回调签名
* @param packageParams
* @param key
* @param charset
* @return
*/
public static boolean isTenpaySign(Map<String, String> map) throws UnsupportedEncodingException {
String charset = "utf-8";
String signFromAPIResponse = map.get("sign");
if (signFromAPIResponse == null || signFromAPIResponse.equals("")) {
System.out.println("API返回的数据签名数据不存在,有可能被第三方篡改!!!");
return false;
}
System.out.println("服务器回包里面的签名是:" + signFromAPIResponse);
// 过滤空 设置 TreeMap
SortedMap<String, String> packageParams = new TreeMap<>();
for (String parameter : map.keySet()) {
String parameterValue = map.get(parameter);
String v = "";
if (null != parameterValue) {
v = parameterValue.trim();
}
packageParams.put(parameter, v);
}
 
StringBuffer sb = new StringBuffer();
Set es = packageParams.entrySet();
Iterator it = es.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String k = (String) entry.getKey();
String v = (String) entry.getValue();
if (!"sign".equals(k) && null != v && !"".equals(v)) {
sb.append(k + "=" + v + "&");
}
}
sb.append("key=" + API_KEY);
// 将API返回的数据根据用签名算法进行计算新的签名,用来跟API返回的签名进行比较
 
// 算出签名
String resultSign = "";
String tobesign = sb.toString();
if (null == charset || "".equals(charset)) {
resultSign = MD5Utils.MD5Encode(tobesign, charset)
.toUpperCase();
} else {
resultSign = MD5Utils.MD5Encode(tobesign, charset)
.toUpperCase();
}
String tenpaySign = ((String) packageParams.get("sign")).toUpperCase();
return tenpaySign.equals(resultSign);
}
 
// 请求方法
public static String httpsRequest(String requestUrl, String requestMethod,
String outputStr) {
try {
 
URL url = new URL(requestUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("content-type",
"application/x-www-form-urlencoded");
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
System.out.println("连接超时:{}" + ce);
} catch (Exception e) {
System.out.println("https请求异常:{}" + e);
}
return null;
}
 
// 退款的请求方法
public static String httpsRequest2(String requestUrl, String requestMethod,
String outputStr) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
StringBuilder res = new StringBuilder("");
FileInputStream instream = new FileInputStream(new File(
"/home/apiclient_cert.p12"));
try {
keyStore.load(instream, "".toCharArray());
} finally {
instream.close();
}
 
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "1313329201".toCharArray()).build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom()
.setSSLSocketFactory(sslsf).build();
try {
 
HttpPost httpost = new HttpPost(
"https://api.mch.weixin.qq.com/secapi/pay/refund");
httpost.addHeader("Connection", "keep-alive");
httpost.addHeader("Accept", "*/*");
httpost.addHeader("Content-Type",
"application/x-www-form-urlencoded; charset=UTF-8");
httpost.addHeader("Host", "api.mch.weixin.qq.com");
httpost.addHeader("X-Requested-With", "XMLHttpRequest");
httpost.addHeader("Cache-Control", "max-age=0");
httpost.addHeader("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
StringEntity entity2 = new StringEntity(outputStr, Consts.UTF_8);
httpost.setEntity(entity2);
System.out.println("executing request" + httpost.getRequestLine());
 
CloseableHttpResponse response = httpclient.execute(httpost);
 
try {
HttpEntity entity = response.getEntity();
 
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: "
+ entity.getContentLength());
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(entity.getContent()));
String text = "";
res.append(text);
while ((text = bufferedReader.readLine()) != null) {
res.append(text);
System.out.println(text);
}
 
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
return res.toString();
 
}
 
// xml解析
public static Map doXMLParse(String strxml) throws JDOMException,
IOException {
strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
 
if (null == strxml || "".equals(strxml)) {
return null;
}
 
Map m = new HashMap();
 
InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(in);
Element root = doc.getRootElement();
List list = root.getChildren();
Iterator it = list.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String k = e.getName();
String v = "";
List children = e.getChildren();
if (children.isEmpty()) {
v = e.getTextNormalize();
} else {
v = getChildrenText(children);
}
 
m.put(k, v);
}
 
// 关闭流
in.close();
 
return m;
}
 
public static String getChildrenText(List children) {
StringBuffer sb = new StringBuffer();
if (!children.isEmpty()) {
Iterator it = children.iterator();
while (it.hasNext()) {
Element e = (Element) it.next();
String name = e.getName();
String value = e.getTextNormalize();
List list = e.getChildren();
sb.append("<" + name + ">");
if (!list.isEmpty()) {
sb.append(getChildrenText(list));
}
sb.append(value);
sb.append("</" + name + ">");
}
}
 
return sb.toString();
}
}
5.3业务类
WeChatPayController类
 
package com.hisap.xql.api.controller;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
 
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
import com.alibaba.fastjson.JSONObject;
import com.hisap.xql.api.common.bean.ResponseJson;
import com.hisap.xql.api.common.constant.CodeMsg;
import com.hisap.xql.api.common.utils.CommonUtil;
import com.hisap.xql.api.common.utils.WeChatPayCommonUtil;
import com.hisap.xql.api.common.wechat.WeChatNotifyResult;
import com.hisap.xql.api.service.WeChatPayService;
 
 
/**
 * @Author: QijieLiu
 * @Description: 微信支付
 * @Date: Created in 16:27 2018/8/14
 */
@Controller
@RequestMapping("/wechatpay")
public class WeChatPayController {
private static final Logger logger = 
LoggerFactory.getLogger(WeChatPayController.class);
@Autowired
private WeChatPayService weChatPayService;
@RequestMapping("/unifiedorder")
@ResponseBody
    public ResponseJson unifiedorder(String orderNo) {
        ResponseJson responseJson = new ResponseJson();
        
        try{
        responseJson = weChatPayService.unifiedorder(new BigDecimal(orderNo));
       
        }catch (Exception e) {
        e.printStackTrace();
logger.error("微信统一下单接口服务端异常,异常信息---" + e.getMessage(), e);
return CommonUtil.createResponseJson(
CodeMsg.SERVER_ERROR_CODE, CodeMsg.SERVER_ERROR_MSG, new JSONObject());
        }
        return responseJson;
    }
}
WeChatPayService接口类
 
package com.hisap.xql.api.service;
 
import java.math.BigDecimal;
 
import com.hisap.xql.api.common.bean.ResponseJson;
import com.hisap.xql.api.common.wechat.WeChatNotifyResult;
 
/**
 * @Author: QijieLiu
 * @Description: 微信支付
 * @Date: Created in 16:35 2018/8/14
 */
public interface WeChatPayService {
ResponseJson unifiedorder(BigDecimal orderNo) throws Exception;
}
WeChatPayServiceImpl接口实现类
 
package com.hisap.xql.api.service.impl;
 
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.alibaba.fastjson.JSONObject;
import com.hisap.xql.api.common.bean.ResponseJson;
import com.hisap.xql.api.common.constant.CodeMsg;
import com.hisap.xql.api.common.utils.Collections3;
import com.hisap.xql.api.common.utils.CommonUtil;
import com.hisap.xql.api.common.wechat.WeChatConfig;
import com.hisap.xql.api.dao.XqlOrderGoodsMapper;
import com.hisap.xql.api.dao.XqlWxRefundLogMapper;
import com.hisap.xql.api.model.XqlOrder;
import com.hisap.xql.api.model.XqlOrderGoods;
import com.hisap.xql.api.model.XqlOrderGoodsExample;
import com.hisap.xql.api.service.WeChatPayService;
import com.hisap.xql.api.service.XqlOrderService;
import com.lijing.wechatpay.conn.PaymentTools;
import com.lijing.wechatpay.util.PayMD5;
 
@Service
public class WeChatPayServiceImpl implements WeChatPayService {
 
private static final Logger logger = LoggerFactory
.getLogger(WeChatPayServiceImpl.class);
 
@Autowired
XqlOrderService xqlOrderServiceImpl;
 
@Autowired
XqlOrderGoodsMapper xqlOrderGoodsMapper;
@Autowired
XqlWxRefundLogMapper xqlWxRefundLogMapper;
 
/**
* 统一下单
* @param characterEncoding
* @param parameters
* @return
*/
@Override
public ResponseJson unifiedorder(BigDecimal orderNo) throws Exception {
ResponseJson responseJson = new ResponseJson();
 
/** 订单主信息 */
XqlOrder xqlOrder = xqlOrderServiceImpl
.selectXqlOrderByOrderNo(orderNo);
if (xqlOrder == null) {
return CommonUtil.createResponseJson(CodeMsg.ORDER_NOT_EXIST_CODE,
CodeMsg.ORDER_NOT_EXIST_MSG, new JSONObject());
}
 
/** 订单明细信息 */
XqlOrderGoodsExample xqlOrderGoodsExample = new XqlOrderGoodsExample();
XqlOrderGoodsExample.Criteria criteria = xqlOrderGoodsExample
.createCriteria();
criteria.andOrderNoEqualTo(orderNo);
 
List<XqlOrderGoods> xqlOrderGoodsList = xqlOrderGoodsMapper
.selectByExample(xqlOrderGoodsExample);
if (Collections3.isEmpty(xqlOrderGoodsList)) {
return CommonUtil.createResponseJson(
CodeMsg.ORDER_ITEM_NOT_EXIST_CODE,
CodeMsg.ORDER_ITEM_NOT_EXIST_MSG, new JSONObject());
}
XqlOrderGoods xqlOrderGoods = xqlOrderGoodsList.get(0);
 
                //待添加验证库存、微信券逻辑
 
TreeMap<String, Object> parameters = new TreeMap<String, Object>();
parameters.put("appid", WeChatConfig.APP_ID);
parameters.put("mch_id", WeChatConfig.MCH_ID);
parameters.put("nonce_str", PayMD5.GetMD5nonce_str());
parameters.put("body", xqlOrderGoods.getGoodsName());
parameters.put("out_trade_no", orderNo.toString());
parameters.put("total_fee", xqlOrder.getOrderAmount());
parameters.put("spbill_create_ip", PaymentTools.getServerIP());
parameters.put("notify_url", WeChatConfig.NOTIFY_URL);
parameters.put("trade_type", WeChatConfig.TRADE_TYPE);
String sign = com.hisap.xql.api.common.wechat.CommonUtil.createSign("UTF-8", parameters);
parameters.put("sign", sign); // 把签名后的数据组装成参数
String tosend = com.hisap.xql.api.common.wechat.CommonUtil.getRequestXml(parameters);
logger.info("微信统一下单请求数据xml:" + tosend);
try {
String result = com.hisap.xql.api.common.wechat.CommonUtil.httpsRequest(WeChatConfig.UNIFIEDORDER_URL, "POST", tosend);
logger.info("微信统一下单返回数据xml:" + result);
Map<String, String> map = null;
        JSONObject jsonObject = new JSONObject();
        SortedMap<String, Object> signParam = new TreeMap<String, Object>();
map = com.hisap.xql.api.common.wechat.CommonUtil.doXMLParse(result);
String return_code = map.get("return_code");
            String prepay_id = null;
            if (return_code.equalsIgnoreCase("SUCCESS")) {
            String result_code = map.get("result_code");
            if(result_code.equalsIgnoreCase("SUCCESS")){
            prepay_id = map.get("prepay_id");//获取到prepay_id
           
                    signParam.put("appid", WeChatConfig.APP_ID);
                    signParam.put("partnerid", WeChatConfig.MCH_ID);
                    signParam.put("prepayid", prepay_id);
                    signParam.put("package", "Sign=WXPay");
                    signParam.put("noncestr", com.hisap.xql.api.common.wechat.CommonUtil.getRandomString(32));//自定义不重复的长度不长于32位
                    signParam.put("timestamp", DateUtil.getSecondTimestamp(new Date()).toString());//此处长度必须为10位
                    String signAgain = com.hisap.xql.api.common.wechat.CommonUtil.createSign("UTF-8", signParam);//再次生成签名
                    signParam.put("sign", signAgain);
                    responseJson = CommonUtil.createResponseJson(
CodeMsg.SUCCESS_CODE, CodeMsg.SUCCESS_MSG,
signParam);
                    
            }else{
            responseJson = CommonUtil.createResponseJson(
            map.get("err_code"), map.get("err_code_des"),
null);
            }
            }else{
            responseJson = CommonUtil.createResponseJson(
            map.get("return_code"), map.get("return_msg"),
null);
            }
} catch (Exception e) {
e.printStackTrace();
logger.error("微信统一下单接口服务端异常,异常信息---" + e.getMessage(), e);
responseJson = CommonUtil.createResponseJson(
CodeMsg.SERVER_ERROR_CODE, CodeMsg.SERVER_ERROR_MSG,
null);
}
 
return responseJson;
}
}
调用之后,返回给APP的内容如下:
 
{
  "code": "200",
  "message": "success",
  "data": {
    "time": "1534908545",
    "response": {
      "appid": "xxxxxx",
      "noncestr": "lKbA8N9J72Swn3XY3JEMVBZLFhWAHaAU",
      "package": "Sign=WXPay",
      "partnerid": "xxxxxx",
      "prepayid": "wx22112827286690ddf3b03c1a3649843158",
      "sign": "FEF21A3A65540ECB1F18DBF58DE57F68",
      "timestamp": "1534908527"
    }
  }
}
这里返回给app二次加签的时候,timestamp必须为string类型,且长度为10位,不然app支付的时候会报验签失败错误。微信支付的统一下单就讲到这里,下一章讲述微信支付结果通知接口开发。

标签: 微信支付
顶一下
(0)
0%
踩一下
(0)
0%

Google提供的广告