微信小程序支付Java服务端开发源码,及那些你不知道的坑(一)

受新冠病毒疫情影响,小程序又被推上风间浪头,曾经的线下实体企业都开始纷纷的转型线上,但目前线上最大的入口莫过于微信。因此小程序成了商家们转型线上的首选。而由于微信自己的生态原因,小程序的在线支付只能使用微信小程序支付。这有让微信支付也越来越火,最近有很多开发者都找我咨询和要微信支付的源码的事情。我今天也再说说这事。

微信小程序支付

说道小程序支付,我要稍稍吐槽一下,微信支付真的搞的很乱。如果你之前项目中已经接入了微信的扫码和App支付,现在要接入小程序支付,大多数人的想法就是,我已经有微信支付的账号了,直接接入使用,那我告诉你,你错了。微信小程序支付是通过申请的小程序开通的微信支付,而微信的扫码和App支付是通过公众号开通的支付,两个不可通用。真是够麻烦,相当让人反感,但我们还得乖乖的用,谁叫人家微信有如此大的生态呢?

不了解微信小程序支付的伙伴们,建议还是先看看开发者文档,知道基础的业务流程。

小程序支付的业务流程图:

å°ç¨åºæ¯ä»æ¶åºå¾

一,小程序支付开发源码

首先创建自己的项目,我这里创建的是SpringBoot的项目。

1,在resources下创建application.yml文件,并添加配置如下:

spring:
  profiles:
    active: dev

##pay config
payment:
  ##wechat config
  wx:
    ##小程序支付
    lte:
      appid: ***
      mchid: ***
      key: ***

2,创建获取配置属性类PayConfig,代码如下:

@Component
@ConfigurationProperties(prefix = "payment")
public class PayConfig {

	//微信支付类型
	//NATIVE--原生支付
	public static final String TRADE_TYPE_NATIVE = "NATIVE";
	//JSAPI--公众号支付-小程序支付
	public static final String TRADE_TYPE_JSAPI = "JSAPI";
	//MWEB--H5支付
	public static final String TRADE_TYPE_MWEB = "MWEB";
	//APP -- app支付
	public static final String TRADE_TYPE_APP = "APP";


	//小程序支付参数
	public static String WX_LTE_APP_ID;
	public static String WX_LTE_MCH_ID;
	public static String WX_LTE_KEY;

	
	//微信支付API
	public static final String WX_PAY_UNIFIED_ORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";


	@Value("${payment.wx.lte.appid}")
	public void setWxLteAppId(String wxLteAppId) {
		WX_LTE_APP_ID = wxLteAppId;
	}
	@Value("${payment.wx.lte.mchid}")
	public void setWxLteMchId(String wxLteMchId) {
		WX_LTE_MCH_ID = wxLteMchId;
	}
	@Value("${payment.wx.lte.key}")
	public void setWxLteKey(String wxLteKey) {
		WX_LTE_KEY = wxLteKey;
	}
}

3,添加启动类:

4,创建一个常量类,放支付涉及的常量信息

public interface PaymentConstants {

    String COMPANY_NAME = "某某某科技有限公司";//用做收款方名称
    String COMPANY_NICK_NAME = "某某某";//收款方名称简称
    String COMPANY_PREFIX = "pay_";

    //项目环境
    String PROJECT_ENV_DEV = "dev";
    String PROJECT_ENV_PRO = "pro";

    String PAYMENT_TITLE = "商品购买";//支付title信息,也可用真实商品名称

    //支付类型,支付宝和微信
    int PAY_TYPE_ALI = 1;
    int PAY_TYPE_WX = 2;

    //微信支付成功后回调url
    String WX_PAY_CALLBACK_URL = "/api/payment/wxNotify";

    //扫描支付
    String PAY_TRADE_TYPE_QR = "QR";
    //App支付
    String PAY_TRADE_TYPE_APP = "APP";
    //小程序支付
    String PAY_TRADE_TYPE_LTE = "LTE";

    String SUCCESS = "SUCCESS";
    String OK = "OK";

5,创建服务接口PaymentService;

public interface PaymentService {

	/**
	 * 小程序支付
	 * @param openId
	 * @param orderNo
	 * @param money
	 * @return
	 * @throws Exception
	 */
	Map<String, String> wxLtePayment(String openId, String orderNo, double money) throws Exception;

	/**
	 * 微信支付回调
	 * @param map
	 * @return
	 * @throws Exception
	 */
	int wxNotify(Map<String, Object> map) throws Exception;


	PaymentRecord queryPaymentStatusById(String orderNo);

}

6,创建服务接口PaymentServiceImpl;

@Service
public class PaymentServiceImpl implements PaymentService {

	private static Logger LOGGER = LoggerFactory.getLogger(PaymentServiceImpl.class);

	@Value("${spring.profiles.active}")
	private String PROJECT_ENV;

	@Value("${server.domain}")
	private String SERVER_DOMAIN;
	
	@Autowired
	private PaymentRecordMapper paymentRecordMapper;
	

	@Override
	@Transactional(readOnly=false,rollbackFor={Exception.class})
	public Map<String, String> wxLtePayment(String openId, String orderNo, double money) throws Exception {
		LOGGER.info("【小程序支付】 统一下单开始, 订单编号="+orderNo);
		SortedMap<String, String> resultMap = new TreeMap<String, String>();
		//生成支付金额
		double payAmount = PayUtil.getPayAmountByEnv(PROJECT_ENV, money);
		//添加或更新支付记录
		int flag = this.addOrUpdatePaymentRecord(orderNo, payAmount, PaymentConstants.PAY_TYPE_WX, PaymentConstants.PAY_TRADE_TYPE_LTE, false, null);
		if(flag < 0){
			resultMap.put("returnCode", "FAIL");
			resultMap.put("returnMsg", "此订单已支付!");
			LOGGER.info("【小程序支付】 此订单已支付!");
		}else if(flag == 0){
			resultMap.put("returnCode", "FAIL");
			resultMap.put("returnMsg", "支付记录生成或更新失败!");
			LOGGER.info("【小程序支付】 支付记录生成或更新失败!");
		}else{
			Map<String,String> resMap = this.wxUnifieldOrder(orderNo, PayConfig.TRADE_TYPE_JSAPI, payAmount,false, openId);
			if(PaymentConstants.SUCCESS.equals(resMap.get("return_code")) && PaymentConstants.SUCCESS.equals(resMap.get("result_code"))){
				resultMap.put("appId", PayConfig.WX_LTE_APP_ID);
				resultMap.put("timeStamp", PayUtil.getCurrentTimeStamp());
				resultMap.put("nonceStr", PayUtil.makeUUID(32));
				resultMap.put("package", "prepay_id="+resMap.get("prepay_id"));
				resultMap.put("signType", "MD5");
				resultMap.put("sign", PayUtil.createSign(resultMap,PayConfig.WX_LTE_KEY));
				resultMap.put("returnCode", "SUCCESS");
				resultMap.put("returnMsg", "OK");
				LOGGER.info("【小程序支付】统一下单成功,返回参数:"+resultMap);
			}else{
				resultMap.put("returnCode", resMap.get("return_code"));
				resultMap.put("returnMsg", resMap.get("return_msg"));
				LOGGER.info("【小程序支付】统一下单失败,失败原因:"+resMap.get("return_msg"));
			}
		}
		return resultMap;
	}

	@Override
	@Transactional(readOnly=false,rollbackFor={Exception.class})
	public int wxNotify(Map<String,Object> map) throws Exception{
		Integer flag = 0;
        //支付订单编号
        String orderNo = (String)map.get("out_trade_no");
        //检验是否需要再次回调刷新数据
        if(this.isNotifyAgain(orderNo)){
        	PaymentRecordExample example = new PaymentRecordExample();
            example.createCriteria().andOrderNoEqualTo(orderNo);
            example.setOrderByClause("id DESC");
            List<PaymentRecord> list = paymentRecordMapper.selectByExample(example);
            if(list!=null && list.size()>0){
            	//当前时间
            	Date currentTime = new Date();
            	PaymentRecord record = list.get(0);
            	record.setTradeNo(String.valueOf(map.get("transaction_id")));
            	record.setStatus(Boolean.TRUE);
            	record.setUpdateTime(currentTime);
            	//更新条件
            	PaymentRecordExample where = new PaymentRecordExample();
            	where.createCriteria().andRecordIdEqualTo(record.getRecordId()).andStatusEqualTo(Boolean.FALSE);
            	flag = paymentRecordMapper.updateByExampleSelective(record,where);
            	LOGGER.info("【微信充值回调】 记录更新成功,订单值ID="+orderNo);
            	if(flag > 0){
            	    PaymentNotify paymentNotify = new PaymentNotify();
                	paymentNotify.setRecordId(record.getRecordId());
                	paymentNotify.setOrderNo(record.getOrderNo());
                	paymentNotify.setTradeNo(record.getTradeNo());
                	paymentNotify.setCreateTime(new Date());
                	paymentNotify.setStatus(true);
                	if(paymentNotifyMapper.insert(paymentNotify) > 0){
                		LOGGER.info("【微信支付回调】 提醒信息生成成功!");
                	}
            	}else{
            		PaymentNotify paymentNotify = new PaymentNotify();
                	paymentNotify.setRecordId(record.getRecordId());
                	paymentNotify.setOrderNo(record.getOrderNo());
                	paymentNotify.setTradeNo(record.getTradeNo());
                	paymentNotify.setCreateTime(new Date());
                	paymentNotify.setStatus(false);
                	if(paymentNotifyMapper.insert(paymentNotify) > 0){
                		LOGGER.info("【微信支付回调】 提醒信息生成成功!");
                	}
                }
                LOGGER.info("【微信支付回调】 订单支付成功,订单号:"+orderNo);
            }
        }
        return flag;
	}


	@Override
	@Transactional(readOnly=true,rollbackFor={Exception.class})
	public PaymentRecord queryPaymentStatusByNo(String OrderNo){
		PaymentRecordExample example = new PaymentRecordExample();
		example.createCriteria().andOrderNoEqualTo(OrderNo);
		example.setOrderByClause("id DESC");
		List<PaymentRecord> list = paymentRecordMapper.selectByExample(example);
		if(list != null && list.size()>0 && list.get(0).getStatus()){
			return list.get(0);
		}
		return null;
	}
	/**
	 * <p>微信支付统一下单</p>
	 *
	 * @param orderNo 订单编号
	 * @param tradeType 支付类型
	 * @param payAmount 支付类型
	 * @param noLtePay 非小程序支付
	 * @return
	 * @throws Exception
	 */
	private Map<String,String> wxUnifieldOrder(String orderNo, String tradeType, double payAmount, boolean noLtePay, String openid) throws Exception{
    	//封装参数
        SortedMap<String,String> paramMap = new TreeMap<String,String>();
        String appId = noLtePay?PayConfig.WX_APP_ID:PayConfig.WX_LTE_APP_ID;
		String mchId = noLtePay?PayConfig.WX_MCH_ID:PayConfig.WX_LTE_MCH_ID;
        paramMap.put("appid", appId);
        paramMap.put("mch_id", mchId);
        paramMap.put("nonce_str", PayUtil.makeUUID(32));
        paramMap.put("body", PaymentConstants.COMPANY_NAME);
        paramMap.put("out_trade_no", orderNo);
        paramMap.put("total_fee", PayUtil.moneyToIntegerStr(payAmount));
        paramMap.put("spbill_create_ip", PayUtil.getLocalIp());
        paramMap.put("notify_url", this.getNotifyUrl(PaymentConstants.PAY_TYPE_WX));
        paramMap.put("trade_type", tradeType);
        if (!noLtePay) {
			paramMap.put("openid",openid);
		}
		String payKey = noLtePay?PayConfig.WX_KEY:PayConfig.WX_LTE_KEY;
        paramMap.put("sign", PayUtil.createSign(paramMap,payKey));
        //转换为xml
        String xmlData = PayUtil.mapToXml(paramMap);
        //请求微信后台,获取预支付ID
        String resXml = HttpUtils.postData(PayConfig.WX_PAY_UNIFIED_ORDER, xmlData);
        LOGGER.info("【微信支付】 统一下单响应:\n"+resXml);
        return PayUtil.xmlStrToMap(resXml);
    }
	
	/**
	 * <p>添加或更新支付记录</p>
	 *
	 * @param orderNo
	 * @param payAmount
	 * @param payType
	 * @return
	 * @throws Exception 
	 */
	private int addOrUpdatePaymentRecord(String orderNo, double payAmount, int payType, String tradeType, boolean isPayment, String tradeNo) throws Exception{
		//添加或更新数据库的支付记录逻辑
        // 写自己的实现代码
	}
}

7,支付工具栏PayUtil

public class PayUtil {

	static Logger log = LogManager.getLogger(PayUtil.class.getName());
	/**
	 * 获取当前机器的ip
	 *
	 * @return String
	 */
	public static String getLocalIp(){
		InetAddress ia=null;
		String localip = null;
        try {
            ia=ia.getLocalHost();
            localip=ia.getHostAddress();
        } catch (Exception e) {
            e.printStackTrace();
        }
		return localip;
        
	}
	
	/**
	 * Map转换为 Xml
	 * 
	 * @param map
	 * @return Xml
	 * @throws Exception
	 */
	public static String mapToXml(SortedMap<String, String> map) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        //防止XXE攻击
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);
        DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = documentBuilder.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: map.keySet()) {
            String value = map.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString();
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    }

	
	/**
	 * 创建签名Sign
	 * 
	 * @param key
	 * @param parameters
	 * @return
	 */ 
	public static String createSign(SortedMap<String,String> parameters,String key){  
        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();  
            if(entry.getValue() != null || !"".equals(entry.getValue())) {
            	String v = String.valueOf(entry.getValue());
            	if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {
            		sb.append(k + "=" + v + "&");
            	}
            }  
        }  
        sb.append("key=" + key);  
        String sign = MD5Util.MD5Encode(sb.toString(), "UTF-8").toUpperCase();  
        return sign;  
    }
    
	
	/**
	 * XML转换为Map
	 * 
	 * @param strXML
	 * @return Map
	 * @throws Exception
	 */
	public static Map<String, Object> getMapFromXML(String strXML) throws Exception {
        try {
            Map<String, Object> data = new HashMap<String, Object>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            //防止XXE攻击
            documentBuilderFactory.setXIncludeAware(false);
            documentBuilderFactory.setExpandEntityReferences(false);
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return data;
        } catch (Exception ex) {
            throw ex;
        }
	}
    
	/**
	 * 生成随机数
	 * 
	 * @return
	 */
	public static String makeUUID(int len) {
		return UUID.randomUUID().toString().replaceAll("-", "").substring(0, len);
	}
	
	/**
     * 获取当前的Timestamp
     * 
     * @return
     */
    public static String getCurrentTimeStamp() {
        return Long.toString(System.currentTimeMillis()/1000);
    }

    /**
     * 获取当前的时间
     * @return
     */
    public static long getCurrentTimestampMs() {
        return System.currentTimeMillis();
    }
    
    /**
     * 生成订单号
     * 
     * @return
     */
    public static String generateOrderNo() {	
    	SimpleDateFormat sdf  = new SimpleDateFormat("yyMMdd");
        return sdf.format(new Date())+makeUUID(16);
    }
	
    /**
	 * 获取当前工程url
	 * 
	 * @param request
	 * @return
	 */
	public static String getCurrentUrl(HttpServletRequest request){
		return request.getScheme() +"://" + request.getServerName()  + ":" +request.getServerPort() +request.getContextPath();
	}
	
	/**
	 * Xml字符串转换为Map
	 * 
	 * @param xmlStr
	 * @return
	 */
	public static Map<String,String> xmlStrToMap(String xmlStr){
        Map<String,String> map = new HashMap<String,String>();
        Document doc;
        try {
            doc = DocumentHelper.parseText(xmlStr);
            Element root = doc.getRootElement();
            List children = root.elements();
            if(children != null && children.size() > 0) {
                for(int i = 0; i < children.size(); i++) {
                    Element child = (Element)children.get(i);
                    map.put(child.getName(), child.getTextTrim());
                }
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return map;
    }
	
	public static String testXml(){
		return "<xml><appid><![CDATA[wx2421b1c4370ec43b]]></appid><attach><![CDATA[支付测试]]></attach><bank_type><![CDATA[CFT]]></bank_type><fee_type><![CDATA[CNY]]></fee_type> <is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[10000100]]></mch_id><nonce_str><![CDATA[5d2b6c2a8db53831f7eda20af46e531c]]></nonce_str><openid><![CDATA[oUpF8uMEb4qRXf22hE3X68TekukE]]></openid> <out_trade_no><![CDATA[WeChat Pay test]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code> <return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[B552ED6B279343CB493C5DD0D78AB241]]></sign><sub_mch_id><![CDATA[10000100]]></sub_mch_id> <time_end><![CDATA[20140903131540]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[JSAPI]]></trade_type><transaction_id><![CDATA[1004400740201409030005092168]]></transaction_id></xml>";
	}

	
	public static String getSceneInfo(String wapUrl,String name){
		Map<String,Map<String,String>> map = new HashMap<String, Map<String,String>>();
		if(!StringUtils.isEmpty(wapUrl) && !StringUtils.isEmpty(name)){
			/*{"h5_info": {"type":"Wap","wap_url": "https://pay.qq.com","wap_name": "腾讯充值"}}*/
			Map<String,String> childmap = new TreeMap<String, String>();
			childmap.put("type", "Wap");
			childmap.put("wap_url",wapUrl);
			childmap.put("wap_name", name);
			map.put("h5_info", childmap);
			return JSON.toJSONString(map);
		}
		return null;
	}
	

    /**
     * 转换金额型到整型
     * @param money
     * @return
     */
    public static String moneyToIntegerStr(Double money){
        BigDecimal decimal = new BigDecimal(money);
        int amount = decimal.multiply(new BigDecimal(100))
            .setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        return String.valueOf(amount);
    }

    /** 
     * 除去数组中的空值和签名参数
     * @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 env
     * @param money
     * @param money
     * @return
     */
    public static double getPayAmountByEnv(String env, Double money){
    	double pay_money = 0.01;
    	//测试环境
    	if("dev".equals(env)){
			return 0.01;
    	}else{
    		//生成环境
    		return money;
    	}
    }
}

8,Controller接口编写

@RestController
@RequestMapping(value = "/api/payment/")
public class PaymentController {

	private static Logger logger = LoggerFactory.getLogger(PaymentController.class);

	@Value("${server.domain}")
	private String serverDomain;
	@Autowired
	private PaymentService paymentService;

	/**
	 * <p>微信小程序支付接口</p>
	 * 必传参数:openId, orderNo, payAmount
	 *
	 * @param request
	 * @param paymentBo
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="ltePay", method=RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
	public ResultData toPay(HttpServletRequest request, @RequestBody PaymentBo paymentBo) throws Exception {
		if (paymentBo == null || paymentBo.getOpenId() == null || paymentBo.getOrderNo() == null || paymentBo.getPayAmount() == null) {
			throw new ParamException();
		} else if (paymentBo.getPayAmount() < 0.01) {
			return ResultData.fail("订单金额有误,请确认!");
		}else{
			logger.info("【小程序支付服务】请求订单编号: ["+paymentBo.getOrderNo()+"]");
			Map<String, String> resMap = paymentService.wxLtePayment(paymentBo.getOpenId(), paymentBo.getOrderNo(), paymentBo.getPayAmount());
			if("SUCCESS".equals(resMap.get("returnCode")) && "OK".equals(resMap.get("returnMsg"))){
				//统一下单成功
				resMap.remove("returnCode");
				resMap.remove("returnMsg");
				logger.info("【小程序支付服务】支付下单成功!");
				return ResultData.ok(resMap);
			}else{
				logger.info("【小程序支付服务】支付下单失败!原因:"+resMap.get("returnMsg"));
				return ResultData.fail(resMap.get("returnMsg"));
			}
		}
	}
	
	/**
	 * 微信支付完成回调Api
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
    @RequestMapping(value="wxNotify")
	public void wxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
 		InputStream inputStream =  request.getInputStream();
 		//获取请求输入流
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len=inputStream.read(buffer))!=-1){
            outputStream.write(buffer,0,len);
        }
        outputStream.close();
        inputStream.close();
        Map<String,Object> map = BeanToMap.getMapFromXML(new String(outputStream.toByteArray(),"utf-8"));
        logger.info("【微信支付回调】 回调数据: \n"+map);
        String resXml = "";
        String returnCode = (String) map.get("return_code");
        if ("SUCCESS".equalsIgnoreCase(returnCode)) {
            String returnmsg = (String) map.get("result_code");
            if("SUCCESS".equals(returnmsg)){
	            //支付成功
	            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
	                     + "<return_msg><![CDATA[OK]]></return_msg>"+"</xml>";
            }else{
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
                logger.info("支付失败:"+resXml);
            }
        }else{
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
            logger.info("【订单支付失败】");
        }
        
        logger.info("【微信支付回调响应】 响应内容:\n"+resXml);
        //做出响应
        response.getWriter().print(resXml);
	}
	
	/**
	 * <p>查询订单支付是否完成</p>
	 *
	 * @param orderNo
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
    @GetMapping(value="queryPayStatus")
	public ResultData queryPayStatus(String orderNo) throws Exception {
		if (StringUtils.isEmpty(orderNo)) {
			throw new ParamException();
		}
		PaymentRecord record = paymentService.queryPaymentStatusById(orderNo);
		if(record != null){
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("companyName", PaymentConstants.COMPANY_NAME);
			map.put("OrderNo", record.getOrderNo());
			map.put("payAmount",record.getPayAmont());
			map.put("payMethod",PaymentConstants.getPayMethod(String.valueOf(record.getPayMethod())));
			map.put("tradeNo",record.getTradeNo());
			map.put("payTime",record.getUpdateTime());
			map.put("payStatus",record.getStatus());
			return ResultData.ok(map);
		}else{
			return ResultData.fail("未支付!");
		}
	}
	
}

9,Controller接收参数Bo

public class PaymentBo {

    /**支付类型:1-支付宝;2-微信*/
    private Integer payType;
    /**客户openId*/
    private String openId;
    /**订单编号*/
    private String orderNo;
    /**支付金额*/
    private Double payAmount;

    public Integer getPayType() {
        return payType;
    }

    public String getOpenId() {
        return openId;
    }

    public String getOrderNo() {
        return orderNo;
    }

    public Double getPayAmount() {
        return payAmount;
    }

    public void setPayType(Integer payType) {
        this.payType = payType;
    }

    public void setOpenId(String openId) {
        this.openId = openId;
    }

    public void setOrderNo(String orderNo) {
        this.orderNo = orderNo;
    }

    public void setPayAmount(Double payAmount) {
        this.payAmount = payAmount;
    }
}

10,Controller接口返回类封装:

public class ResultData<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer code;
    private String message;
    private T data;

    public Integer getCode() {
        return code;
    }
    public String getMessage() {
        return message;
    }
    public T getData() {
        return data;
    }
    public void setCode(Integer code) {
        this.code = code;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public void setData(T data) {
        this.data = data;
    }

    public ResultData() {}

    public ResultData(ResultCodeEnums status, T data) {
        this(status.getCode(), status.getMessage(), data);
    }

    public ResultData(Integer code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public static <T> ResultData<T> ok(String message){
        return new ResultData<T>(ResultCodeEnums.SUCCESS, null);
    }

    public static <T> ResultData<T> ok(T data){
        return new ResultData<T>(ResultCodeEnums.SUCCESS,data);
    }

    public static <T> ResultData<T> ok(String message,T data){
        return new ResultData<T>(ResultCodeEnums.SUCCESS.getCode(), message, data);
    }

    public static <T> ResultData<T> fail(String message){
        return fail(null);
    }

    public static <T> ResultData<T> fail(T data){
        return new ResultData<T>(ResultCodeEnums.FAIL, data);
    }

    public static <T> ResultData<T> fail(String message,T data){
        return new ResultData<T>(ResultCodeEnums.FAIL.getCode(), message, data);
    }
}

二,小程序端(获取统一下单返回参数发起支付)

在小程序端,发起支付请求到,Java后台的统一下单接口返回prepay_id等参数,然后封装调起微信的js方法:wx.requestPayment(OBJECT),具体参考文档:官方文档

测试一把:

本篇代码是我们运行两年电商项目的源码,目前做的已经很完整健壮,由于依赖和工具类等很多,不能全部贴出来,还请谅解。如果需要,请扫描添加公众号,联系本人获取其他代码或支付项目。

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页