Java对接微信支付详解

一、介绍

微信支付对于我们日常来说,并不陌生,也许我们日常都在用。现在我就讲一下微信支付的流程是怎么实现的,都有哪些步骤,以及注意点。

支付流程图:

Java对接微信支付详解_第1张图片

参数说明如图:

Java对接微信支付详解_第2张图片

二、开发步骤

1、首先需要开通商户号,获取商户mch_id、mch_secret(密钥)

2、开通小程序或公众号,获取小程序或公众号appid、secret(密钥)

3、除了前面2步的准备环境,也就进入主流程步骤,分为3步如下:

3-1:封装有必要的微信支付参数并拉取微信支付API

3-2:对封装的参数进行提取并开始支付阶段,需要二次签名加密

3-3:当3-2步骤支付成功时,会调用回调函数,进行二次签名校验

注意:第一次签名必须保证与二次签名保持一致,否则会导致微信支付失败。【前面2步不讲】
一、封装并校验微信支付相关参数【相关工具类后面附上】
 /**
     * 微信支付
     *
     * @param orderPayVo
     * @return
     */
    @Override
    public ResponseEntity<Object> payment(MiniOrderPayVo orderPayVo) {
     
        if (orderPayVo == null) {
     
            return HttpResponseSupport.error(HttpStatus.NOT_FOUND, "订单支付数据不能为空,请检查参数再试", "订单支付数据不能为空,请检查参数再试");
        }
        String orderNo = orderPayVo.getOrderNo();
        if (StringUtil.isEmpty(orderNo)) {
     
            return HttpResponseSupport.miniSuccess(MiniBusinessCodeEnum.USER_ORDER_NO, null);
        }
        Double money = orderPayVo.getMoney();
        String uuid = orderPayVo.getUuid();
        if (StringUtils.isBlank(uuid)){
     
            log.info("预支付订单uuid为:"+uuid);
            return HttpResponseSupport.error(HttpStatus.NOT_FOUND,"订单uuid不能为空","订单uuid不能为空");
        }
        if (money <= 0) {
     
            return HttpResponseSupport.miniSuccess(MiniBusinessCodeEnum.USER_MONEY, null);
        }
        //计算总价
        BigDecimal amountPrice = new BigDecimal(money);
        amountPrice = amountPrice.multiply(new BigDecimal("100"));	// 将分转换为元
        String totalFee = getTotalFee(amountPrice);		// 订单金额处理

        Map<String, String> data = new HashMap<>(16);
        data.put("body", "xxx产品");
        data.put("detail", "xxx产品");
        data.put("out_trade_no", orderNo); // 订单号或外部流水号
        data.put("fee_type", "CNY");	   // 金额类型	默认CNY

        data.put("total_fee", totalFee);        //经过计算出来价格 单位为分
        data.put("spbill_create_ip", WXProperty.WX_IP);	// 终端ip
        data.put("notify_url", WXProperty.WX_MINI_NOTIFY_URL);	// 回调url
        data.put("trade_type", "JSAPI");	// 所使用的交易类型 以小程序支付为例

        data.put("openid", queryUserInfo());	// 用户openid

        Map<String, String> resp = WXMninPaySupport.unifiedOrder(wxPayConfig, data);
        if (resp == null) {
     
            return HttpResponseSupport.error(HttpStatus.CONFLICT, "支付失败,请稍后重试!", "支付失败,请稍后重试");
        }
        //记录订单的uuid, 订单编号 以及 预支付uuid
        resp.get("prepay_id"); // 预支付订单ID
        resp.put("orderId", orderNo); // 订单编号
        resp.put("uuid", uuid);
        resp.put("total_fee",totalFee);
        //开始支付
        return wxPayInfo(resp);
    }
二、开始调起微信支付
 /**
     * 开始支付接口
     *
     * @param resp
     * @return
     */
    public ResponseEntity<Object> wxPayInfo(Map<String, String> resp) {
     
        String prePayId = resp.get("prepay_id");

        String timeStamp = System.currentTimeMillis() / 1000 + "";
        String nonceStr = com.github.wxpay.sdk.WXPayUtil.generateNonceStr();

        Map<String, String> data2 = new HashMap<>(10);
        data2.put("appId", resp.get("appid"));
        data2.put("timeStamp", timeStamp);
        data2.put("nonceStr", nonceStr);

        String packages = "prepay_id=" + resp.get("prepay_id");
        data2.put("package", packages);
        data2.put("signType", "MD5");
        String sign2 = null;
        try {
     
            sign2 = com.github.wxpay.sdk.WXPayUtil.generateSignature(data2, WXProperty.WX_MCH_SECRET);
        } catch (Exception e) {
     
            e.printStackTrace();
        }

        /*----------------------------------------------------*/
        MiniWXPayVO result = new MiniWXPayVO();
        result.setPrepayId(prePayId);
        result.setNonceStr(nonceStr);
        result.setPackageStr("prepay_id=" + prePayId);
        result.setTimeStamp(new Long(System.currentTimeMillis() / 1000).toString());
        result.setSignType("MD5");	// 采用MD5加密算法
        result.setPaySign(sign2);
        result.setOrderId(resp.get("orderId"));
        result.setUuid(resp.get("uuid"));
        return HttpResponseSupport.success(result);
    }
三、支付成功后自动调用回调函数
/**
     * 微信支付回调
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    public void wxPayNotify(HttpServletRequest request, HttpServletResponse response) {
     
        WxCallbackLogs logs = new WxCallbackLogs();
        StringBuilder sb = null;
        //获取主机ip
        String remoteAddr = request.getRemoteAddr();
        logs.setRemoteAddr(remoteAddr);
        //获取请求url
        String requestUrl = request.getRequestURL().toString();
        logs.setRequestUrl(requestUrl);
        //获取回调响应状态
        int status = response.getStatus();
        logs.setStatus(status);
        try {
     
            BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
            String line = null;
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
     
                sb.append(line);
            }
            br.close();
        } catch (IOException e) {
     
            e.printStackTrace();
        }
        //sb为微信返回的xml
        String notifyXml = sb.toString();
        logs.setNotityContent(notifyXml);
        String resXml = "";
        log.info("接收到的报文:{}" , notifyXml);
        try {
     
            @SuppressWarnings("unchecked")
            Map<String, String> map = PayUtil.doXMLParse(notifyXml);    //解析接收过来的xml文件
            String returnCode = map.get("return_code");
            logs.setReturnCode(returnCode);
            String resultCode = map.get("result_code");
            logs.setResultCode(resultCode);
            if ("SUCCESS".equals(returnCode) && "SUCCESS".equals(resultCode)) {
     
                //验证签名是否正确
                Map<String, String> validParams = PayUtil.paraFilter(map);  //回调验签时需要去除sign和空值参数
                String validStr = PayUtil.createLinkString(validParams);//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
                String sign = PayUtil.sign(validStr, WXProperty.WX_MCH_SECRET, "utf-8").toUpperCase();//拼装生成服务器端验证的签名
                // 因为微信回调会有八次之多,所以当第一次回调成功了,那么我们就不再执行逻辑了
                String ordersSn = map.get("out_trade_no");//商户订单号
                logs.setOrdersSn(ordersSn);
                String amountpaid = map.get("total_fee");//实际支付的订单金额:单位 分
                String openid = map.get("openid");
                logs.setOpenid(openid);
                BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);//将分转换成元-实际支付金额:元
                logs.setAmountPay(amountPay);
                //根据微信官网的介绍,此处不仅对回调的参数进行验签,还需要对返回的金额与系统订单的金额进行比对等
                if (sign.equals(map.get("sign"))) {
     
                    //处理业务逻辑    1、更新订单状态
                    UserOrderVo orderVo = queryUserOrderInfoByOrderNo(ordersSn);
                    if (orderVo != null) {
     
                        //更新状态信息
                        orderVo.setUuid(orderVo.getUuid());
                        orderVo.setPayStatus(2);
                        orderVo.setPayPrice(amountPay);
                        orderVo.setOpenId(openid);
                        Integer result = updOrderInfo(orderVo);
                        if (result > 0) {
     
                            log.info("更新订单状态成功!!!");
                        }
                        //通知微信服务器已经支付成功
                        resXml = "" + ""
                                + "" + " ";
                    }
                } else {
     
                    log.info("微信支付回调失败!签名不一致");
                }
            } else {
     
                resXml = "" + ""
                        + "" + " ";
            }
        } catch (Exception e) {
     
            e.printStackTrace();
        }
        logs.setUuid(RandomNumberGenerate.generateNonceStr());
        logs.setResult(resXml);
        //添加回调日志信息
        paymentMapper.addWxCallBackLogs(logs);
        try {
     
            log.info(resXml);
            log.info("微信支付回调数据结束");
            BufferedOutputStream out = new BufferedOutputStream(
                    response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } catch (IOException e) {
     
            e.printStackTrace();
        }
    }
四、微信支付相关工具类
/**
     * 处理微信金额
     * //  public static final BigDecimal WXTOTALFEE = new BigDecimal("1");
     * @param amountPrice
     * @return
     */
    @Override
    public String getTotalFee(BigDecimal amountPrice) {
     
        String totalFee = amountPrice.intValue() + "";
        //当支付金额小于等于1时,只需付0.01
        BigDecimal totalFeeTemp = new BigDecimal(totalFee);
        if (WXConstant.WXTOTALFEE.compareTo(totalFeeTemp) > -1) {
     
            totalFee = "1";
        }
        return totalFee;
    }

public static Map<String, String> unifiedOrder(CommonWXPayConfig customsWXPayConfig, Map<String, String> data) {
     
        WXPay wxPay = new WXPay(customsWXPayConfig, WXPayConstants.SignType.MD5);
        if (data.size() < 1) {
     
            return null;
        }
        try {
     
            Map<String, String> resp = wxPay.unifiedOrder(data);
            String returnCode = resp.get(WXConstant.WX_PAY_RERUEN_CODE);// return_code
            String resultCode = resp.get(WXConstant.WX_PAY_RESULT_CODE);// result_code
            if (StringUtils.equals(WXConstant.WX_PAY_SUCCESS, resultCode) && StringUtils.equals(WXConstant.WX_PAY_SUCCESS, returnCode)) {
     	// SUCCESS
                log.info("微信拉起支付结果:{}", resp);
                return resp;
            } else {
     
                log.error("微信拉起支付失败结果:{}", resp);
                return null;
            }
        } catch (Exception e) {
     
            log.error("微信支付异常结果:{}", e.getMessage());
            return null;
        }
    }
PayUtil:
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=" + key;
        String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset)).toUpperCase();
        if (mysign.equals(sign)) {
     
            return true;
        } else {
     
            return false;
        }
    }

    /**
     * @param content
     * @param charset
     * @return
     * @throws java.security.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<>(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
     * @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对象转字符串
	 * @param  泛型占位符
	 * @param obj T
	 * @return String
	 */
	public static <T> String toJson(T obj) {
     
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").enableComplexMapKeySerialization().create();
		return gson.toJson(obj);
	}
}
CommonWXPayConfig:
@Configuration
public class CommonWXPayConfig implements WXPayConfig {
     
    private byte[] certData;

    @Override
    public String getAppID() {
     
        return WXProperty.WX_MINI_APP_ID;	// 小程序或公众号appid
    }

    @Override
    public String getMchID() {
     
        return WXProperty.WX_MCH_ID;		// 商户ID
    }

    @Override
    public String getKey() {
     
        return WXProperty.WX_MCH_SECRET;	// 商户密钥
    }

    @Override
    public InputStream getCertStream() {
     
        return new ByteArrayInputStream(this.certData);
    }

    @Override
    public int getHttpConnectTimeoutMs() {
     
        return 8000;
    }

    @Override
    public int getHttpReadTimeoutMs() {
     
        return 10000;
    }
}
wxpay-sdk:
<dependency>
    <groupId>com.github.wxpay</groupId>
    <artifactId>wxpay-sdk</artifactId>
    <version>0.0.3</version>
</dependency>

最后,完整的微信支付就写完了,希望对你们有所帮助!!!

你可能感兴趣的:(java,小程序,微信支付,小程序,java)