微信支付(weixin-java-pay)

curlykale發表於2018-04-26

1. 專案依賴

增加pom.xml檔案中增加依賴包。weixin-java-pay是GitHub開源的一個微信支付工具包

<dependency>
	<groupId>com.github.binarywang</groupId>
	<artifactId>weixin-java-pay</artifactId>
	<version>3.0.0</version>
</dependency>
複製程式碼

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;
    }

}

複製程式碼

相關文章