微信支付(weixin-java-pay)

1. 项目依赖

增加pom.xml文件中增加依赖包。weixin-java-pay是GitHub开源的一个微信支付工具包


	com.github.binarywang
	weixin-java-pay
	3.0.0

复制代码

2. contorller代码

package com.xxx.sub.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayBillBaseResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.github.binarywang.wxpay.util.SignUtils;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.gson.Gson;
import com.xxx.sub.entity.SubWorkerInfoEntity;
import com.xxx.sub.entity.SysPayInfoEntity;
import com.xxx.sub.service.SubWorkerInfoServiceI;
import com.xxx.sub.service.SysPayInfoServiceI;
import com.xxx.sub.util.SubCodeUtil;
import com.sun.star.bridge.oleautomation.Decimal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.util.PropertiesUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import org.jeecgframework.p3.core.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Title: Controller
 * @Description: 微信支付
 * @author onlineGenerator
 * @date 2018-02-07 17:45:09
 * @version V1.0
 *
 */
@Api(value="wxPayController",description="微信支付",tags="RESTWxPayController")
@Controller
@RequestMapping("/wxPayController")
public class RESTWxPayController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(RESTWxPayController.class);
	@Autowired
	WXPayConfig config;
	@Autowired
	private SubWorkerInfoServiceI subWorkerInfoService;

	/**
	 * 产生订单接口
	 * @param payType 支付类型
	 * @param id 支付信息id
	 * @return
	 * @throws WxPayException
	 */
	@RequestMapping(value = "/generatePay/{payType}/{id}",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="微信统一下单接口1")
	public ResponseMessage generatePay2(@ApiParam(required=true) @PathVariable(value="payType") String payType,@ApiParam(required=true) @PathVariable(value="id") String id) throws WxPayException {
		String tradeNo = SubCodeUtil.getNum();
		String busId = "123131313";
		Integer fee = 1;
		WxPayUnifiedOrderRequest.WxPayUnifiedOrderRequestBuilder builder = WxPayUnifiedOrderRequest.newBuilder();
		WxPayUnifiedOrderRequest request  = builder.body(payType)
				.totalFee(fee).outTradeNo(tradeNo)
				.productId("1000000123")
				.spbillCreateIp("0.0.0.0")
				.tradeType("APP").build();
		request.setSignType("MD5");
		WxPayService wxPayService = getWxPayService();
		WxPayAppOrderResult o = wxPayService.createOrder(request);
		System.out.println(o.toString());
		// 存储支付信息到数据库
		SysPayInfoEntity payInfoEntity = new SysPayInfoEntity();
		payInfoEntity.setBusId(Integer.valueOf(id));
		payInfoEntity.setBusType(payType);
		payInfoEntity.setBusCode(busId);
		payInfoEntity.setCreateTime(new Date());
		payInfoEntity.setOrderNo(tradeNo);
		payInfoEntity.setPayState(0);//支付状态:0未支付1支付成功2支付失败3退款成功
		payInfoEntity.setPayType("wxPay");
		payInfoEntity.setOrderDetail(new Gson().toJson(0));
		try {
			sysPayInfoServiceI.save(payInfoEntity);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.success(o);
	}

	/**
	 * 接收支付返回的消息
	 * @param
	 */
	@RequestMapping(value="/parseOrderNotifyResult",method = RequestMethod.POST)
	@ApiOperation(value="接收支付返回的消息")
	@ResponseBody
	public String parseOrderNotifyResult(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("============支付回调开始");
		try {
			String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
			WxPayService wxPayService = getWxPayService();
			WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);
			System.out.println(result.toString());
			// 结果正确
			String orderId = result.getOutTradeNo();
			String tradeNo = result.getTransactionId();
			//String totalFee = WxPayBaseResult.feeToYuan(result.getTotalFee());
			//自己处理订单的业务逻辑,需要判断订单是否已经支付过,否则可能会重复调用
			System.out.println("============支付回调结束");
			return WxPayNotifyResponse.success("处理成功!");
		} catch (Exception e) {
			logger.error("微信回调结果异常,异常原因{}" + e.getMessage());
			return WxPayNotifyResponse.fail(e.getMessage());
		}
	}

	/**
	 * 加载配置文件,生成微信payservice对象
	 * @return
	 */
	private WxPayService getWxPayService() {
		PropertiesUtil util = new PropertiesUtil("wx.properties");
		WxPayConfig payConfig = new WxPayConfig();
		payConfig.setAppId(util.readProperty("appid"));
		payConfig.setMchId(util.readProperty("mchid"));
		payConfig.setMchKey(util.readProperty("mchkey"));
		payConfig.setNotifyUrl(util.readProperty("notifyurl"));
		WxPayService wxPayService = new WxPayServiceImpl();
		wxPayService.setConfig(payConfig);
		return wxPayService;
	}

}
复制代码

3. service、entity代码省略

service就是业务操作、entity主要是存储支付订单信息的实体

4. util

package com.nyis.sub.util;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 流水号生成
 */

public class SubCodeUtil {
    
    /**
     * 获取现在时间
     * @return返回字符串格式yyyyMMddHHmmss
     */
    public static String getStringDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = formatter.format(currentTime);
        System.out.println("TIME:::"+dateString);
        return dateString;
    }

    /**
     * 由年月日时分秒+3位随机数
     * 生成流水号
     * @return
     */
    public static String getNum(){
        String t = getStringDate();
        int x=(int)(Math.random()*900)+100;
        String serial = t + x;
        return serial;
    }

}

复制代码

转载于:https://juejin.im/post/5ae19366518825671f2f79a1

你可能感兴趣的:(微信支付(weixin-java-pay))