java 后台微信小程序统一下单支付、以及二次签名(亲测可用)

java 后台微信小程序统一下单支付、以及二次签名(仅供参考)

本人使用的是ssh框架,不过没关系,都是业务代码,不影响,话不多说,直接贴代码

一、首先去官网下载java的sdk,因为这里需要用到sdk里面的一些方法,感兴趣的话可以直接研究sdk中给的代码,这里是本人参考别人然后看了sdk中的代码后自己写的,也能实现统一下单,sdk下载地址小程序支付SDK与DEMO下载
二、下载后将demo引入到自己的工程里面,可以选择性的引入,也可以全部引入,我是全部引入进去的
java 后台微信小程序统一下单支付、以及二次签名(亲测可用)_第1张图片
引入之后就是处理报错问题啦,就是导入各种jar包,jar包的话就不给出了,直接在maven上下载就可以

  • 三、创建Configure.java ,以及RandomStringGenerator.java (后面会用到)
  • 一些常亮配置Configure .java
public class Configure {
	// 商户支付秘钥
	private static String key = "XXXXXXXXXXXXX";
	//小程序ID 
	private static String appID = "XXXXXXXXXXXXX";
	//商户号
	private static String mch_id = "XXXXXXXXXXXXX";
	// 小程序的secret
	private static String secret = "XXXXXXXXXXXXX";
	
	public static String getKey() {
		return key;
	}
	public static void setKey(String key) {
		Configure.key = key;
	}
	public static String getAppID() {
		return appID;
	}
	public static void setAppID(String appID) {
		Configure.appID = appID;
	}
	public static String getMch_id() {
		return mch_id;
	}
	public static void setMch_id(String mch_id) {
		Configure.mch_id = mch_id;
	}
	public static String getSecret() {
		return secret;
	}
	public static void setSecret(String secret) {
		Configure.secret = secret;
	}
	
	
}
  • 随机字符串生成的类RandomStringGenerator .java
package com.qu.welfare.controller.mob.pay.wxpay.plugins;
import java.util.Random;
 
/**
* 随机字符串生成
*
*/
public class RandomStringGenerator {
 /**
  * 获取一定长度的随机字符串
  * @param length 指定字符串长度
  * @return 一定长度的字符串
  */
  public static String getRandomStringByLength(int 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();
  }
}


  • 四、创建发送请求的类HttpRequest.java(缺少的jar包自己导入啦,请求的时候可能会出现请求失败的问题,这时候检查下,是不是jar包是不是有冲突哦)
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;

import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
 
public class HttpRequest {

 //连接超时时间,默认10秒
  private static final int socketTimeout = 10000;
 
  //传输超时时间,默认30秒
  private static final int connectTimeout = 30000;
 /**
  * post请求
  * @throws IOException
  * @throws ClientProtocolException
  * @throws NoSuchAlgorithmException
  * @throws KeyStoreException
  * @throws KeyManagementException
  * @throws UnrecoverableKeyException
  */
 public static String sendPost(String url, Object xmlObj) throws ClientProtocolException, IOException, UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException {
   
  HttpPost httpPost = new HttpPost(url);
  //解决XStream对出现双下划线的bug
    XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
    xStreamForRequestPostData.alias("xml", xmlObj.getClass());
    //将要提交给API的数据对象转换成XML格式数据Post给API
    String postDataXML = xStreamForRequestPostData.toXML(xmlObj);
 
    //得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
    StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
    httpPost.addHeader("Content-Type", "text/xml");
    httpPost.setEntity(postEntity);
 
    //设置请求器的配置
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
    httpPost.setConfig(requestConfig);
   
    HttpClient httpClient = HttpClients.createDefault();
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity entity = response.getEntity();
    String result = EntityUtils.toString(entity, "UTF-8");
    return result;
 }
 public static String sendPost(String url, String signXml) throws ClientProtocolException, IOException, UnrecoverableKeyException, KeyManagementException, KeyStoreException, NoSuchAlgorithmException {
	   
	  HttpPost httpPost = new HttpPost(url);
	  //解决XStream对出现双下划线的bug
	    XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));
	 
	    //得指明使用UTF-8编码,否则到API服务器XML的中文不能被成功识别
	    StringEntity postEntity = new StringEntity(signXml, "UTF-8");
	    httpPost.addHeader("Content-Type", "text/xml");
	    httpPost.setEntity(postEntity);
	 
	    //设置请求器的配置
	    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
	    httpPost.setConfig(requestConfig);
	   
	    HttpClient httpClient = HttpClients.createDefault();
	    HttpResponse response = httpClient.execute(httpPost);
	    HttpEntity entity = response.getEntity();
	    String result = EntityUtils.toString(entity, "UTF-8");
	    return result;
	 }
}


  • 五、创建接收统一下单调用微信接口返回的参数的类OrderReturnInfo.java
 /**
 * 接收统一下单调用微信接口返回的参数
 * @author Administrator
 *   */
public class OrderReturnInfo {
  private String return_code;
  private String return_msg;
  private String result_code;
  private String appid;
  private String mch_id;
  private String nonce_str;
  private String sign;
  private String prepay_id;
  private String trade_type;
  private String err_code;
  private String err_code_des;
 public String getReturn_code() {
  return return_code;
 }
 public void setReturn_code(String return_code) {
  this.return_code = return_code;
 }
 public String getReturn_msg() {
  return return_msg;
 }
 public void setReturn_msg(String return_msg) {
  this.return_msg = return_msg;
 }
 public String getResult_code() {
  return result_code;
 }
 public void setResult_code(String result_code) {
  this.result_code = result_code;
 }
 public String getAppid() {
  return appid;
 }
 public void setAppid(String appid) {
  this.appid = appid;
 }
 public String getMch_id() {
  return mch_id;
 }
 public void setMch_id(String mch_id) {
  this.mch_id = mch_id;
 }
 public String getNonce_str() {
  return nonce_str;
 }
 public void setNonce_str(String nonce_str) {
  this.nonce_str = nonce_str;
 }
 public String getSign() {
  return sign;
 }
 public void setSign(String sign) {
  this.sign = sign;
 }
 public String getPrepay_id() {
  return prepay_id;
 }
 public void setPrepay_id(String prepay_id) {
  this.prepay_id = prepay_id;
 }
 public String getTrade_type() {
  return trade_type;
 }
 public void setTrade_type(String trade_type) {
  this.trade_type = trade_type;
 }
public String getErr_code() {
	return err_code;
}
public void setErr_code(String err_code) {
	this.err_code = err_code;
}
public String getErr_code_des() {
	return err_code_des;
}
public void setErr_code_des(String err_code_des) {
	this.err_code_des = err_code_des;
}
 
}
  • 六、接下来就是最后的业务处理代码了,我是写在Controller里面的,你可以把代码写在你的service中,这里需要写几个常量,注意了

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jason.framework.mvc.spring.BaseController;
import com.jason.framework.util.StringUtil;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
 
/**
 * 
 * @author jxliu
 *
 */
@Controller()
@RequestMapping(value = "")
public class WxpayController extends BaseController{
   
    private static final long serialVersionUID = 1L;
    private static final Logger L = Logger.getLogger(WxpayController.class);
    //支付回调地址(你自己的请求地址,可以自己随意配置啦,写在这方便你理解)
    private String notify_url = "https://xinhuo.21stf.org/mob/pay/wxpay/weixin/callback/wxNotify.do";
    //交易类型(这里是小程序)
    private final String trade_type = "JSAPI";
    //统一下单API接口链接(微信官方的接口)
    private final String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
 
    
    @RequestMapping(value = "/payment")
    public ResponseEntity payment(HttpServletRequest request,String money, String openid,String body){
    	if (StringUtil.isEmpty(money)) {
			return renderData(false, "参数错误:money不能为空!", null);
		}
    	if (StringUtil.isEmpty(openid)) {
			return renderData(false, "参数错误:openid不能为空!", null);
		}
    	if (StringUtil.isEmpty(body)) {
			return renderData(false, "参数错误:body不能为空!", null);
		}
    	Map data = new HashMap();
         Map map = new HashMap();
         data.put("appid", Configure.getAppID());//公众账号ID
         data.put("mch_id", Configure.getMch_id());//商户号
         data.put("nonce_str", RandomStringGenerator.getRandomStringByLength(32));//随机字符串
         data.put("openid", openid);//用户标识
         data.put("body", body);//商品描述
         data.put("out_trade_no", RandomStringGenerator.getRandomStringByLength(18));//商户订单号
         data.put("fee_type", "CNY");//
         data.put("total_fee", money);//标价金额
         data.put("spbill_create_ip", XXXXXXXXX);//终端IP
         data.put("notify_url", notify_url);//回调地址
         data.put("trade_type", trade_type);  //交易类型
         //生成签名
         String signXml= "";
         try {
         	//调用demo里面的sign生成方法
         	signXml = WXPayUtil.generateSignedXml(data, Configure.getKey(),SignType.MD5);
         	String result = HttpRequest.sendPost(url, signXml);
         	System.out.println(result);
         	XStream xStream = new XStream();
         	xStream.setupDefaultSecurity(xStream);
         	//出于安全考虑,这里必须限制类型,不然会报错
         	xStream.allowTypes(new Class[]{OrderReturnInfo.class});
            xStream.alias("xml", OrderReturnInfo.class);
  
             OrderReturnInfo returnInfo = (OrderReturnInfo)xStream.fromXML(result);
             // 二次签名
             if ("SUCCESS".equals(returnInfo.getReturn_code()) && returnInfo.getReturn_code().equals(returnInfo.getResult_code())) {
            	 long time = System.currentTimeMillis()/1000;
            	 
                 //生成签名(官方给出来的签名方法)
                 Map map2 = new HashMap();
                 map2.put("appId", Configure.getAppID());
                 map2.put("timeStamp", String.valueOf(time));
                 //这边的随机字符串必须是第一次生成sign时,微信返回的随机字符串,不然小程序支付时会报签名错误
                 map2.put("nonceStr", returnInfo.getNonce_str());
                 map2.put("package", "prepay_id=" + returnInfo.getPrepay_id());
                 map2.put("signType", "MD5");
                 
                 String sign2 = WXPayUtil.generateSignature(map2, Configure.getKey(), SignType.MD5);
                 System.out.println("二次签名的sign2----->"+sign2);
                 //无效的签名方法
                 //String sign1 = Signature.getSign(signInfo);
                 Map payInfo = new HashMap();
                 payInfo.put("timeStamp", String.valueOf(time));
                 payInfo.put("nonceStr", returnInfo.getNonce_str());
                 payInfo.put("prepay_id",returnInfo.getPrepay_id());
                 payInfo.put("signType", "MD5");
                 payInfo.put("paySign", sign2);
                 map.put("status", 200);
                 map.put("msg", "统一下单成功!");
                 map.put("data", payInfo);
  
                 // 此处可以写唤起支付前的业务逻辑
                 
                 // 业务逻辑结束
                 return renderData(true, "Success!", map);
             }
             map.put("status", 500);
             map.put("msg", "统一下单失败!");
             map.put("data", returnInfo);
             return renderData(true, "Success!", map);
         } catch (Exception e) {
 			e.printStackTrace();
 		}
         return renderData(true, "Success!", map);
     }
    
    /**
     * 微信小程序支付成功回调函数
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/weixin/callback/wxNotify")
    public void wxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine()) != null){
            sb.append(line);
        }
        br.close();
        //sb为微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";
        System.out.println("接收到的报文:" + notityXml);
 
        @SuppressWarnings("unchecked")
		Map map = PayUtil.doXMLParse(notityXml);
 
        String returnCode = (String) map.get("return_code");
        if("SUCCESS".equals(returnCode)){
            //验证签名是否正确
            Map validParams = PayUtil.paraFilter(map);  //回调验签时需要去除sign和空值参数
            String validStr = PayUtil.createLinkString(validParams);//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
            String sign = PayUtil.sign(validStr, Configure.getKey(), "utf-8").toUpperCase();//拼装生成服务器端验证的签名
            // 因为微信回调会有八次之多,所以当第一次回调成功了,那么我们就不再执行逻辑了
           
            //根据微信官网的介绍,此处不仅对回调的参数进行验签,还需要对返回的金额与系统订单的金额进行比对等
            if(sign.equals(map.get("sign"))){
                /**此处添加自己的业务逻辑代码start**/
                  // bla bla bla....
                /**此处添加自己的业务逻辑代码end**/
                //通知微信服务器已经支付成功
                resXml = "" + ""
                        + "" + " ";
            } else {
                System.out.println("微信支付回调失败!签名不一致");
            }
        }else{
            resXml = "" + ""
                    + "" + " ";
        }
        System.out.println(resXml);
        System.out.println("微信支付回调数据结束");
 
        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }
}

、到这就结束了,踩了很多坑,网上有很多生成sign的方法,尝试了很多,生成的签名跟微信的签名都不一致,最终还是用的微信的签名方法,下面是踩坑介绍,仅供参考哦

  • 第一次签名基本没什么坑,必传参数要传,必传参数API
  • 第二次签名:第一个注意点java 后台微信小程序统一下单支付、以及二次签名(亲测可用)_第2张图片
    第二个注意点:
    java 后台微信小程序统一下单支付、以及二次签名(亲测可用)_第3张图片
    八、到此为止已经可以用了,如有不足欢迎指出来哦
  • 补充下PayUtil
package com.qu.welfare.controller.mob.pay.wxpay.plugins;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
 
public class PayUtil {
  /**
  * 签名字符串
  * @param text 需要签名的字符串
  * @param key 密钥
  * @param input_charset 编码格式
  * @return 签名结果
  */
  public static String sign(String text, String key, String input_charset) {
    text = text + "&key=" + key;
    return DigestUtils.md5Hex(getContentBytes(text, input_charset));
  }
  /**
  * 签名字符串
  * @param text 需要签名的字符串
  * @param sign 签名结果
  * @param key 密钥
  * @param input_charset 编码格式
  * @return 签名结果
  */
  public static boolean verify(String text, String sign, String key, String input_charset) {
    text = text + key;
    String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
    if (mysign.equals(sign)) {
      return true;
    } else {
      return false;
    }
  }
  /**
  * @param content
  * @param charset
  * @return
  * @throws SignatureException
  * @throws UnsupportedEncodingException
  */
  public static byte[] getContentBytes(String content, String charset) {
    if (charset == null || "".equals(charset)) {
      return content.getBytes();
    }
    try {
      return content.getBytes(charset);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
    }
  }
 
  private static boolean isValidChar(char ch) {
    if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
      return true;
    if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
      return true;// 简体中文汉字编码
    return false;
  }
  /**
  * 除去数组中的空值和签名参数
  * @param sArray 签名参数组
  * @return 去掉空值与签名参数后的新签名参数组
  */
  public static Map<String, String> paraFilter(Map<String, String> sArray) {
    Map<String, String> result = new HashMap<String, String>();
    if (sArray == null || sArray.size() <= 0) {
      return result;
    }
    for (String key : sArray.keySet()) {
      String value = sArray.get(key);
      if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
          || key.equalsIgnoreCase("sign_type")) {
        continue;
      }
      result.put(key, value);
    }
    return result;
  }
  /**
  * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
  * @param params 需要排序并参与字符拼接的参数组
  * @return 拼接后字符串
  */
  public static String createLinkString(Map<String, String> params) {
    List<String> keys = new ArrayList<String>(params.keySet());
    Collections.sort(keys);
    String prestr = "";
    for (int i = 0; i < keys.size(); i++) {
      String key = keys.get(i);
      String value = params.get(key);
      if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
        prestr = prestr + key + "=" + value;
      } else {
        prestr = prestr + key + "=" + value + "&";
      }
    }
    return prestr;
  }
  /**
  *
  * @param requestUrl 请求地址
  * @param requestMethod 请求方法
  * @param outputStr 参数
  */
  public static String httpRequest(String requestUrl,String requestMethod,String outputStr) {
    // 创建SSLContext
    StringBuffer buffer = null;
    try {
      URL url = new URL(requestUrl);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod(requestMethod);
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.connect();
      //往服务器端写内容
      if (null != outputStr) {
        OutputStream os = conn.getOutputStream();
        os.write(outputStr.getBytes("utf-8"));
        os.close();
      }
      // 读取服务器端返回的内容
      InputStream is = conn.getInputStream();
      InputStreamReader isr = new InputStreamReader(is, "utf-8");
      BufferedReader br = new BufferedReader(isr);
      buffer = new StringBuffer();
      String line = null;
      while ((line = br.readLine()) != null) {
        buffer.append(line);
      }
      br.close();
    }catch(Exception e){
      e.printStackTrace();
    }
    return buffer.toString();
  }
  public static String urlEncodeUTF8(String source){
    String result=source;
    try {
      result=java.net.URLEncoder.encode(source, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return result;
  }
  /**
  * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
  * @param strxml
  * @return
  * @throws JDOMException
  * @throws IOException
  */
  public static Map doXMLParse(String strxml) throws Exception {
    if(null == strxml || "".equals(strxml)) {
      return null;
    }
 
    Map m = new HashMap();
    InputStream in = String2Inputstream(strxml);
    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;
  }
  /**
  * 获取子结点的xml
  * @param children
  * @return String
  */
  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();
  }
  public static InputStream String2Inputstream(String str) {
    return new ByteArrayInputStream(str.getBytes());
  }
}

你可能感兴趣的:(java日常)