Commit 02b37e12 authored by cy's avatar cy

支付代码整理

parent f1359fdd
......@@ -13,7 +13,7 @@ import java.util.SortedMap;
/**
* @author chnegyan
*/
public interface TestWxPayService {
public interface WxPayService {
/**
* pc端微信支付
* @Param 支付信息
......
......@@ -9,6 +9,7 @@ import cn.wisenergy.model.vo.AddLimitVo;
import cn.wisenergy.service.app.AliPayService;
import cn.wisenergy.service.app.UserLimitService;
import cn.wisenergy.service.common.Common;
import cn.wisenergy.service.util.WxPayUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
......@@ -64,7 +65,8 @@ public class AliPayServiceImpl implements AliPayService {
AlipayClient alipayClient = new DefaultAlipayClient(Common.PAY_URL, APP_ID, PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
String tradeNo = "21" + System.currentTimeMillis();
//生成唯一订单号
String tradeNo = WxPayUtil.getOrderIdByUUId();
//支付成功跳转地址
alipayRequest.setReturnUrl(Common.RETURN_URL_PC);
//支付回调地址
......@@ -81,7 +83,7 @@ public class AliPayServiceImpl implements AliPayService {
try {
AlipayTradePagePayResponse response = alipayClient.pageExecute(alipayRequest);
form = response.getBody();
System.out.println(form);
log.info("AliPayServiceImpl[]doPost[]alipayClient.result.form:"+form);
httpResponse.setContentType("text/html;charset=UTF-8");
//直接将完整的表单html输出到页面
httpResponse.getWriter().write(form);
......@@ -115,12 +117,12 @@ public class AliPayServiceImpl implements AliPayService {
}
AlipayClient alipayClient = new DefaultAlipayClient(Common.PAY_URL, APP_ID, PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
String tradeNo = "21" + System.currentTimeMillis();
//生成唯一订单号
String tradeNo = WxPayUtil.getOrderIdByUUId();
//支付成功跳转地址
alipayRequest.setReturnUrl(Common.RETURN_URL_WAP);
//支付后回调地址
alipayRequest.setNotifyUrl(Common.NOTIFY_URL);
alipayRequest.setBizContent("{" +
"\"out_trade_no\":\"" + tradeNo + "\"," +
"\"total_amount\":" + payPageDto.getTotal() + "," +
......@@ -133,7 +135,7 @@ public class AliPayServiceImpl implements AliPayService {
try {
AlipayResponse response = alipayClient.pageExecute(alipayRequest);
form = response.getBody();
System.out.println(form);
log.info("AliPayServiceImpl[]wapAliPay[]alipayClient.result.form:"+form);
httpResponse.setContentType("text/html;charset=UTF-8");
//直接将完整的表单html输出到页面
httpResponse.getWriter().write(form);
......
package cn.wisenergy.service.app.impl;
import cn.wisenergy.common.utils.R;
import cn.wisenergy.model.dto.PayPageDto;
import cn.wisenergy.model.dto.PayQueryDto;
import cn.wisenergy.model.vo.AddLimitVo;
import cn.wisenergy.service.app.UserLimitService;
import cn.wisenergy.service.app.WxPayService1;
import cn.wisenergy.service.httpClient.WechatPayHttpClientBuilder;
import cn.wisenergy.service.httpClient.auth.AutoUpdateCertificatesVerifier;
import cn.wisenergy.service.httpClient.auth.PrivateKeySigner;
import cn.wisenergy.service.httpClient.auth.WechatPay2Credentials;
import cn.wisenergy.service.httpClient.auth.WechatPay2Validator;
import cn.wisenergy.service.httpClient.util.PemUtil;
import cn.wisenergy.service.util.SignDemo;
import cn.wisenergy.service.wxpay.WxCommon;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.After;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.crypto.IllegalBlockSizeException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.UUID;
/**
* @author 86187
*/
@Service
@Slf4j
public class WxPayService1Impl implements WxPayService1 {
@Autowired
private UserLimitService userLimitService;
/**
* 商户号
*/
private static String mchId = WxCommon.MCHID;
// 商户证书序列号
private static String mchSerialNo = WxCommon.SERIAL_NO;
// api密钥
private static String apiV3Key = WxCommon.SECRET_KEY;
// 你的商户私钥
private static String privateKey = "-----BEGIN PRIVATE KEY-----\n" + WxCommon.PRIVATE_KEY
+ "-----END PRIVATE KEY-----\n";
private CloseableHttpClient httpClient;
private AutoUpdateCertificatesVerifier verifier;
@Before
public void setup() throws IOException {
PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
new ByteArrayInputStream(privateKey.getBytes("utf-8")));
//使用自动更新的签名验证器,不需要传入证书
verifier = new AutoUpdateCertificatesVerifier(
new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),
apiV3Key.getBytes("utf-8"));
httpClient = WechatPayHttpClientBuilder.create()
.withMerchant(mchId, mchSerialNo, merchantPrivateKey)
.withValidator(new WechatPay2Validator(verifier))
.build();
}
@After
public void after() throws IOException {
httpClient.close();
}
@Override
public R<String> wxPay(PayPageDto payPageDto) {
if (null == payPageDto || null == payPageDto.getTotal()) {
return R.error("入参不能为空!");
}
HttpPost httpPost = new HttpPost();
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Accept", "application/json");
long timestamp = System.currentTimeMillis() / 1000;
String nonceStr = UUID.randomUUID().toString().replace("-", "");
String method = "POST";
String tradeNo = "21" + System.currentTimeMillis();
HttpUrl httpurl = HttpUrl.parse(WxCommon.WX_PAY_URL_pc);
//构造签名参数
JSONObject jsonObject = new JSONObject();
jsonObject.put("appid", WxCommon.APP_ID);
jsonObject.put("mchid", WxCommon.MCHID);
jsonObject.put("description", "充值");
jsonObject.put("out_trade_no", tradeNo);
jsonObject.put("notify_url", WxCommon.NOTIFY_URL);
jsonObject.put("amount", payPageDto.getTotal());
String sign = null;
try {
sign = SignDemo.getToken(method, httpurl, jsonObject.toJSONString(), nonceStr, timestamp);
httpPost.setHeader("Authorization", "WECHATPAY2-SHA256-RSA2048" + " " + sign);
//增加用户查询次数和充值记录
AddLimitVo addLimitVo = new AddLimitVo();
addLimitVo.setPayMoney(payPageDto.getTotal());
addLimitVo.setPayType(2);
addLimitVo.setUserId(payPageDto.getUserId());
R<Boolean> booleanR = userLimitService.addLimit(addLimitVo);
if (booleanR.getCode()==1) {
return R.error("用户查询次数添加失败");
}
return R.ok(0,"充值成功");
} catch (Exception e) {
return R.ok(1,"充值失败");
}
}
@Override
public R<String> queryWx(PayQueryDto payQueryDto) throws UnsupportedEncodingException, NoSuchAlgorithmException, SignatureException, InvalidKeySpecException, InvalidKeyException {
if (null == payQueryDto || StringUtils.isBlank(payQueryDto.getOutTradeNo())) {
return R.error("入参不能为空!");
}
long timestamp = System.currentTimeMillis() / 1000;
String nonceStr = UUID.randomUUID().toString().replace("-", "");
String method = "GET";
String url = WxCommon.WX_PAY_QUERY + payQueryDto.getOutTradeNo() + "?mchid=" + WxCommon.MCHID;
HttpUrl httpurl = HttpUrl.parse(url);
//构造签名参数
String sign = SignDemo.getToken(method, httpurl, null, nonceStr, timestamp);
HttpGet httpGet = new HttpGet();
httpGet.addHeader("Content-Type", "application/json");
httpGet.addHeader("Accept", "application/json");
//设置认证信息
httpGet.setHeader("Authorization", "WECHATPAY2-SHA256-RSA2048" + " " + sign);
return null;
}
@Override
public R<String> wx_Pay(PayPageDto payPageDto) throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeySpecException, InvalidKeyException, IllegalBlockSizeException {
HttpPost httpPost = new HttpPost(WxCommon.WX_PAY_URL_pc);
long timestamp = System.currentTimeMillis() / 1000;
String nonceStr = UUID.randomUUID().toString().replace("-", "");
String method = "POST";
String tradeNo = "21" + System.currentTimeMillis();
HttpUrl httpurl = HttpUrl.parse(WxCommon.WX_PAY_URL_pc);
// 请求body参数
String reqdata = "{"
+ "\"time_expire\":\"2021-02-07T10:34:56+08:00\","
+ "\"amount\": {"
+ "\"total\":" + payPageDto.getTotal() + ","
+ "\"currency\":\"CNY\""
+ "},"
+ "\"mchid\":\"" + WxCommon.MCHID + "\","
+ "\"description\":\"Image形象店-深圳腾大-QQ公仔\","
+ "\"notify_url\":\"" + WxCommon.NOTIFY_URL + "\","
+ "\"out_trade_no\":\"" + tradeNo + "\","
+ "\"goods_tag\":\"WXG\","
+ "\"appid\":\"" + WxCommon.APP_ID + "\","
+ "\"attach\":\"自定义数据说明\","
+ "\"detail\": {"
+ "\"invoice_id\":\"wx123\","
+ "\"goods_detail\": ["
+ "{"
+ "\"goods_name\":\"iPhoneX 256G\","
+ "\"wechatpay_goods_id\":\"1001\","
+ "\"quantity\":1,"
+ "\"merchant_goods_id\":\"商品编码\","
+ "\"unit_price\":828800"
+ "},"
+ "{"
+ "\"goods_name\":\"iPhoneX 256G\","
+ "\"wechatpay_goods_id\":\"1001\","
+ "\"quantity\":1,"
+ "\"merchant_goods_id\":\"商品编码\","
+ "\"unit_price\":828800"
+ "}"
+ "],"
+ "\"cost_price\":608800"
+ "},"
+ "\"scene_info\": {"
+ "\"store_info\": {"
+ "\"address\":\"广东省深圳市南山区科技中一道10000号\","
+ "\"area_code\":\"440305\","
+ "\"name\":\"腾讯大厦分店\","
+ "\"id\":\"0001\""
+ "},"
+ "\"device_id\":\"013467007045764\","
+ "\"payer_client_ip\":\"14.23.150.211\""
+ "}"
+ "}";
StringEntity reqEntity = new StringEntity(
reqdata, ContentType.create("application/json", "utf-8"));
httpPost.setEntity(reqEntity);
httpPost.addHeader("Accept", "application/json");
//构造签名参数
//构造签名参数
JSONObject jsonObject = new JSONObject();
jsonObject.put("appid", WxCommon.APP_ID);
jsonObject.put("mchid", WxCommon.MCHID);
jsonObject.put("description", "充值");
jsonObject.put("out_trade_no", tradeNo);
jsonObject.put("notify_url", WxCommon.NOTIFY_URL);
jsonObject.put("amount", payPageDto);
String token = SignDemo.getToken(method, httpurl, jsonObject.toJSONString(), nonceStr, timestamp);
httpPost.setHeader("Authorization", "WECHATPAY2-SHA256-RSA2048" + " " + token);
//1.创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//完成签名并执行请求
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = response.getEntity();
String content = EntityUtils.toString(httpEntity, "utf8");
System.out.println(content.length());
return R.ok(response.toString());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
response.close();
}
return null;
}
}
......@@ -5,7 +5,7 @@ import cn.wisenergy.mapper.PayRecordMapper;
import cn.wisenergy.model.app.PayRecord;
import cn.wisenergy.model.dto.PayPageDto;
import cn.wisenergy.model.vo.AddLimitVo;
import cn.wisenergy.service.app.TestWxPayService;
import cn.wisenergy.service.app.WxPayService;
import cn.wisenergy.service.app.UserLimitService;
import cn.wisenergy.service.util.MapToXmlUtils;
import cn.wisenergy.service.util.WxPayUtil;
......@@ -33,7 +33,7 @@ import static com.baomidou.mybatisplus.core.toolkit.Constants.MD5;
*/
@Service
@Slf4j
public class TestWxPayServiceImpl implements TestWxPayService {
public class WxPayServiceImpl implements WxPayService {
//统一下单接口链接
public static String unifiedOrderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
......@@ -68,19 +68,22 @@ public class TestWxPayServiceImpl implements TestWxPayService {
if (null == payPageDto || null == payPageDto.getTotal()) {
return R.error("入参不能为空");
}
String tradeNo = "21" + System.currentTimeMillis();
//生成唯一订单号
String tradeNo = WxPayUtil.getOrderIdByUUId();
//商品id
String product_id = "10" + System.currentTimeMillis();
String time_expire=WxPayUtil.getOrderExpireTime(2*60*1000L);
//支付过期时间
String time_expire = WxPayUtil.getOrderExpireTime(2 * 60 * 1000L);
//生成预支付订单,充值结果设为失败(result=1)
try {
//生成【统一下单API】所需参数的接口
String orderInfo = WxPayUtil.createOrderInfo(payPageDto,tradeNo, product_id,time_expire, appid, mchid, key);
System.out.println(orderInfo);
String orderInfo = WxPayUtil.createOrderInfo(payPageDto, tradeNo, product_id, time_expire, appid, mchid, key);
log.info("WxPayServiceImpl[]wxPay[]xmlInfo.orderInfo:"+orderInfo);
//调用统一下单接口
Map<String, String> map = unifiedOrder(unifiedOrderUrl,orderInfo);
Map<String, String> map = unifiedOrder(unifiedOrderUrl, orderInfo);
String code_url = map.get("code_url");
log.info("支付返回信息:", map.get("return_msg"));
if (map!=null && "SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
log.info("WxPayServiceImpl[]wxPcPay[]unifiedOrder.result.map:" + map);
if (map != null && "SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
PayRecord payRecord = new PayRecord();
payRecord.setMoney(payPageDto.getTotal());
payRecord.setResult(1);
......@@ -90,10 +93,9 @@ public class TestWxPayServiceImpl implements TestWxPayService {
payRecordMapper.add(payRecord);
}
Map<String, String> objMap = new HashMap<>();
System.out.println("code_url:" + code_url);
objMap.put("tradeNo",tradeNo);
objMap.put("time_expire",time_expire);
objMap.put("code_url",code_url);
objMap.put("tradeNo", tradeNo);
objMap.put("time_expire", time_expire);
objMap.put("code_url", code_url);
return R.ok("0", objMap);
} catch (Exception e) {
e.printStackTrace();
......@@ -109,18 +111,19 @@ public class TestWxPayServiceImpl implements TestWxPayService {
if (null == payPageDto || null == payPageDto.getTotal()) {
return R.error("入参不能为空");
}
String tradeNo = "21" + System.currentTimeMillis();
//生成唯一订单号
String tradeNo = WxPayUtil.getOrderIdByUUId();
//生成预支付订单,充值结果设为失败(result=1)
try {
//生成【统一下单API】所需参数的接口
String orderInfo = WxPayUtil.createOrderInfoH5(payPageDto,tradeNo, request, appid, mchid, key);
System.out.println(orderInfo);
String orderInfo = WxPayUtil.createOrderInfoH5(payPageDto, tradeNo, request, appid, mchid, key);
log.info("WxPayServiceImpl[]h5WxPay[]xmlInfo.orderInfo:"+orderInfo);
//调用统一下单接口
Map<String, String> map = unifiedOrder(unifiedOrderUrl,orderInfo);
Map<String, String> map = unifiedOrder(unifiedOrderUrl, orderInfo);
String urlString = URLEncoder.encode("https://jygkzy.com/#/history", "GBK");
String mweb_url = map.get("mweb_url") + "&redirect_url=" + urlString;
log.info("返回信息:", map.get("return_msg"));
if (map!=null && "SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
log.info("WxPayServiceImpl[]h5WxPay[]unifiedOrder.result.map:" + map);
if (map != null && "SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
PayRecord payRecord = new PayRecord();
payRecord.setMoney(payPageDto.getTotal());
payRecord.setResult(1);
......@@ -148,16 +151,16 @@ public class TestWxPayServiceImpl implements TestWxPayService {
SortedMap<String, String> mapParams = new TreeMap<>();
//随机字符串
String nonce_str = RandomStringUtils.randomAlphanumeric(16);
String tradeNo = "21" + System.currentTimeMillis();
//生成唯一订单号
String tradeNo = WxPayUtil.getOrderIdByUUId();
//生成预支付订单,充值结果设为失败(result=1)
try {
//生成【统一下单API】所需参数的接口
String orderInfo = WxPayUtil.createOrderInfoWx(payPageDto, tradeNo, nonce_str, Applets_ID,secrt_key, mchid, key);
System.out.println(orderInfo);
String orderInfo = WxPayUtil.createOrderInfoWx(payPageDto, tradeNo, nonce_str, Applets_ID, secrt_key, mchid, key);
log.info("WxPayServiceImpl[]WxPayApplets[]xmlInfo.orderInfo:"+orderInfo);
//调用统一下单接口
Map<String, String> map = unifiedOrder(unifiedOrderUrl,orderInfo);
String return_msg = map.get("return_msg");
log.info("支付返回信息:", return_msg);
Map<String, String> map = unifiedOrder(unifiedOrderUrl, orderInfo);
log.info("WxPayServiceImpl[]WxPayApplets[]unifiedOrder.result.map:" + map);
if ("SUCCESS".equals(map.get("return_code")) && "SUCCESS".equals(map.get("result_code"))) {
PayRecord record = new PayRecord();
record.setMoney(payPageDto.getTotal());
......@@ -176,10 +179,10 @@ public class TestWxPayServiceImpl implements TestWxPayService {
mapParams.put("timeStamp", timeStamp + "");
mapParams.put("signType", MD5);
//二次签名
String paySign = WxPayUtil.createSign(mapParams,key);
String paySign = WxPayUtil.createSign(mapParams, key);
mapParams.put("paySign", paySign);
}
return R.ok("0",mapParams);
return R.ok("0", mapParams);
} catch (Exception e) {
e.printStackTrace();
return R.error("支付参数获取失败");
......@@ -190,7 +193,8 @@ public class TestWxPayServiceImpl implements TestWxPayService {
/***
* 微信统一下单
*/
public Map<String, String> unifiedOrder(String url,String info) throws Exception {
public Map<String, String> unifiedOrder(String url, String info) throws Exception {
log.info("开始微信统一下单....");
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
//加入数据
conn.setRequestMethod("POST");
......@@ -218,7 +222,7 @@ public class TestWxPayServiceImpl implements TestWxPayService {
*/
@Override
public void wxPayCallBack(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("进入微信回调");
log.info("开始微信回调....");
BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
InputStream inStream = request.getInputStream();
ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
......@@ -255,7 +259,7 @@ public class TestWxPayServiceImpl implements TestWxPayService {
+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
}
}else{
} else {
resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
}
......@@ -272,17 +276,17 @@ public class TestWxPayServiceImpl implements TestWxPayService {
* 订单状态查询
*/
@Override
public R<Map<String,String>> wxQuery(String out_trade_no){
public R<Map<String, String>> wxQuery(String out_trade_no) {
QueryWrapper<PayRecord> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("trade_no",out_trade_no);
queryWrapper.eq("trade_no", out_trade_no);
PayRecord payRecord = payRecordMapper.selectOne(queryWrapper);
Map<String, String> result = new HashMap<>();
result.put("return_code", "SUCCESS");
result.put("result_code", "SUCCESS");
result.put("trade_state", "SUCCESS");
if(payRecord.getResult()==0){
return R.ok(0,result);
}else{
if (payRecord.getResult() == 0) {
return R.ok(0, result);
} else {
return R.error("支付失败");
}
}
......
......@@ -158,4 +158,16 @@ public class WxPayUtil {
return sdf.format(afterDate );
}
/**
* 生成16位唯一订单号
* @return
*/
public static String getOrderIdByUUId() {
int first = new Random(10).nextInt(8) + 1;
int hashCodeV = UUID.randomUUID().toString().hashCode();
if (hashCodeV < 0) {//有可能是负数
hashCodeV = -hashCodeV;
}
return first + String.format("%015d", hashCodeV);
}
}
......@@ -4,8 +4,7 @@ import cn.wisenergy.common.utils.R;
import cn.wisenergy.model.dto.PayPageDto;
import cn.wisenergy.model.dto.PayQueryDto;
import cn.wisenergy.service.app.AliPayService;
import cn.wisenergy.service.app.TestWxPayService;
import cn.wisenergy.service.app.WxPayService1;
import cn.wisenergy.service.app.WxPayService;
import cn.wisenergy.service.common.Common;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
......@@ -22,15 +21,8 @@ import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.crypto.IllegalBlockSizeException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;
import java.util.SortedMap;
......@@ -47,7 +39,7 @@ import java.util.SortedMap;
public class PayController {
@Autowired
private TestWxPayService testWxPayService;
private WxPayService testWxPayService;
@Autowired
private AliPayService aliPayService;
......
package cn.wisenergy.web.admin.controller.app;
import cn.wisenergy.common.utils.R;
import cn.wisenergy.service.util.SubCodeUtil;
import cn.wisenergy.service.wxpay.WxCommon;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayNativeOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author 86187
*/
@Api(tags = "测试微信支付-管理员登录")
@RestController
@RequestMapping("/pay")
@Slf4j
public class TestWxPayController {
/**
* 产生订单接口
*
* @param payType 支付类型
* @param id 支付信息id
* @return
* @throws WxPayException
*/
@RequestMapping(value = "/generatePay/{payType}/{id}", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "微信统一下单接口1")
public R 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("NATIVE").build();
request.setSignType("MD5");
WxPayService wxPayService = getWxPayService();
WxPayNativeOrderResult o = wxPayService.createOrder(request);
System.out.println(o.toString());
return R.ok(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) {
log.error("微信回调结果异常,异常原因{}" + e.getMessage());
return WxPayNotifyResponse.fail(e.getMessage());
}
}
/**
* 加载配置文件,生成微信payservice对象
*
* @return
*/
private WxPayService getWxPayService() {
WxPayConfig payConfig = new WxPayConfig();
String app_id = "wx39c84a7da8e71c32";
String mchid = "1605798036";
String private_key = "yHG21lRpqil1X3fWG0VFytxFuXzxIpRd";
// payConfig.setAppId(WxCommon.APP_ID);
// payConfig.setMchId(WxCommon.MCHID);
// payConfig.setMchKey(WxCommon.PRIVATE_KEY);
payConfig.setAppId(app_id);
payConfig.setMchId(mchid);
payConfig.setMchKey(private_key);
payConfig.setNotifyUrl(WxCommon.NOTIFY_URL);
WxPayService wxPayService = new WxPayServiceImpl();
wxPayService.setConfig(payConfig);
return wxPayService;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment