【项目简述】
最近公司在做微信小程序,我负责给前端提供接口。小程序主要是关于汽车配件商户,我们可以找到附近的汽配店,购买下单支付自己需要的一些汽车配件。
目前系统支持两种支付方式,一种是挂账支付,类似打白条,给客户一定的挂账额度,直接入库;另一种就是微信支付。
【统一下单】
1. 应用场景
要使用微信支付,需要系统先调用统一下单接口在微信支付服务后台生成预支付交易单,返回正确的预支付交易回话标识后再按扫码/JSAPI/APP等不同场景生成交易串调起支付。
2. 接口链接
URL地址:https://api.mch.weixin.qq.com/pay/unifiedorder
3. 实现说明
1)需要先在微信商户平台申请开通支付功能,审核通过后,才能通过微信提供的接口地址使用支付功能;
2)准备一些必要的参数:
字段名 | 变量名 | 描述 |
---|---|---|
公众账号ID | appid | 微信支付分配的公众账号ID(企业号corpid即为此appId) |
商户号 | mch_id | 微信支付分配的商户号 |
随机字符串 | nonce_s$1 | |
公众账号ID | appid | 微信支付分配的公众账号ID(企业号corpid即为此appId) |
签名 | sign | 通过签名算法计算得出的签名值 |
商品描述 | body | 商品简单描述 |
商户订单号 | out_trade_no | 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-*@ ,且在同一个商户号下唯一。 |
标价金额 | total_fee | 订单总金额,单位为分 |
终端IP | spbill_create_ip | APP和网页支付提交用户端ip,Native支付填调用微信支付API的机器IP。 |
通知地址 | notify_url | 异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。 |
交易类型 | trade_type | 取值如下:JSAPI,NATIVE,APP等 |
3)错误码
4)代码实现
/**
* 调用微信统一下单接口
**/
public static ReturnMsg weixinPay(String sn, BigDecimal totalAmount, String description, String sym, HttpServletRequest request) {
String appId = request.getParameter("appId");
String openid = request.getParameter("openid");
String mchId = request.getParameter("mchId");
String apiKey = request.getParameter("apiKey");
if (StringUtils.isBlank(appId) || StringUtils.isBlank(openid) || StringUtils.isBlank(mchId) || StringUtils.isBlank(apiKey)) {
logger.info("appId=" + appId + "; openid=" + openid + "; mchId=" + mchId + "; apiKey=" + apiKey);
return new ReturnMsg("111111", "获取参数失败!");
}
SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
parameterMap.put("appid", appId);
parameterMap.put("mch_id", mchId);
parameterMap.put("nonce_str", randomString);
parameterMap.put("body", description);
parameterMap.put("out_trade_no", sn);
parameterMap.put("fee_type", "CNY");
BigDecimal total = totalAmount.multiply(new BigDecimal(100));
java.text.DecimalFormat df = new java.text.DecimalFormat("0");
parameterMap.put("total_fee", df.format(total).toString());
parameterMap.put("spbill_create_ip", request.getRemoteAddr());
parameterMap.put("notify_url", sym + wxnotify);//"http://xxx.com"
parameterMap.put("trade_type", "JSAPI");
parameterMap.put("openid", openid);
String sign = CommonUtil.createSign("UTF-8", parameterMap, apiKey);
parameterMap.put("sign", sign);
String requestXML = CommonUtil.getRequestXml(parameterMap);
logger.info(requestXML);
String result = CommonUtil.httpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", requestXML);
logger.info(result);
Map<String, String> map = null;
JSONObject jsonObject = new JSONObject();
SortedMap<String, Object> signParam = new TreeMap<String, Object>();
try {
map = CommonUtil.doXMLParse(result);
String return_code = map.get("return_code");
String prepay_id = null;
if (return_code.contains("SUCCESS")) {
prepay_id = map.get("prepay_id");//获取到prepay_id
}
long currentTimeMillis = System.currentTimeMillis();//生成时间戳
long second = currentTimeMillis / 1000L;//(转换成秒)
String seconds = String.valueOf(second).substring(0, 10); //截取前10位
signParam.put("appId", appId);//app_id
signParam.put("package", "prepay_id=" + prepay_id);//默认sign=WXPay
signParam.put("nonceStr", CommonUtil.getRandomString(32));//自定义不重复的长度不长于32位
signParam.put("timeStamp", seconds);//北京时间时间戳
signParam.put("signType", "MD5");//北京时间时间戳
String signAgain = CommonUtil.createSign("", signParam, apiKey);//再次生成签名
signParam.put("paySign", signAgain);
jsonObject.on | IOException e) {
e.printStackTrace();
}
ReturnMsg msg = ReturnMsg.getSuccessMsg();
msg.getData().put("paramterMap", signParam);
return msg;
}
CommonUtil类:
public class CommonUtil {
//微信参数配置
// public static String API_KEY = "aabe26408852e78249d51e7fb9800b7d";
//随机字符串生成
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 = (String) entry.getValue();
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, String apiKey) {
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=" + apiKey);
System.out.println(sb.toString());
String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase();
return sign;
}
/**
* 验证回调签名
* @param packageParams
* @param key
* @param charset
* @return
*/
public static boolean isTenpaySign(Map<String, String> map, String apiKey) 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=" + apiKey);
//将API返回的数据根据用签名算法进行计算新的签名,用来跟API返回的签名进行比较
//算出签名
String resultSign = "";
String tobesign = sb.toString();
if (null == charset || "".equals(charset)) {
resultSign = MD5Util.MD5Encode(tobesign, charset).toUpperCase();
} else {
resultSign = MD5Util.MD5Encode(tobesign, charset).toUpperCase();
}
String tenpaySign = 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();
}
}
MD5Util类:
public class MD5Util {
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" };
}