1.添加微信支付依赖
<!--微信支付-->
<dependency>
<groupId>com.github.wxpay</groupId>
<artifactId>wxpay-sdk</artifactId>
<version>RELEASE</version>
</dependency>
<!--httpclient-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
2.添加配置yml配置文件 如果使用的不是yml 可自行配置
weixin:
appid: wx09c076475bb9xxxx #公众账号ID
partner: 164544xxxx #商户号
partnerkey: zebrainfo20230809wwwcomcn1xxxxxx #商户密钥
notifyurl: http://8de92n.xxxx.cc/pay/info #回调地址
3.自行添加一个service层 (我这边叫PayService)
public interface PayService {
public Object createUrl(CustomerOrder CustomerOrder);
}
4.实现此service层 (其中生成随机订单号使用了一个工具类,可私信我来拿,或你们把随机订单号代码注释,自己去找一个即可)
package com.banma.wxpay;
import com.banma.entity.CustomerOrder;
import com.banma.entity.Enterprise;
import com.banma.mapper.CustomerOrderMapper;
import com.banma.mapper.EnterpriseMapper;
import com.banma.util.HttpClient;
import com.banma.util.OrderCodeFactory;
import com.banma.wxpay.service.PayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
@Service
public class PayServiceImpl implements PayService {
//获取yml中的公众账号ID
@Value("${weixin.appid}")
private String appid;
//获取yml中的商户号
@Value("${weixin.partner}")
private String partner;
@Value("${weixin.partnerkey}")
private String partnerkey;
@Value("${weixin.notifyurl}")
private String notifyurl;
@Autowired
EnterpriseMapper EnterpriseMapper;
@Autowired
CustomerOrderMapper CustomerOrderMapper;
@Override
public Object createUrl(CustomerOrder CustomerOrder) {
//orderId:订单的id,price:需要支付的金额(默认单位为 分 )
Map<String,Object> map = new HashMap<String,Object>();
try {
//判断付款用户是否注册企业
Enterprise enterprise = EnterpriseMapper.findEnterpriseAndEnterpriseIdByEnterpriseName(CustomerOrder.getEnterpriseName());
//查询到没有该企业返回404
if(enterprise == null){
map.put("code","404");
return map;
}
//生成随机订单号
String orderCode = OrderCodeFactory.getOrderCode(enterprise.getEnterpriseId().longValue());
CustomerOrder.setCustomerOrderNumber(orderCode);
CustomerOrder.setEnterpriseId(enterprise.getEnterpriseId());
//设置订单待支付状态
CustomerOrder.setCustomerOrderStart(2);
CustomerOrderMapper.addCustomerOrder(CustomerOrder);
Map<String, String> param = new HashMap<>();
param.put("appid", "wx09c076475bb9xxxx");
param.put("mch_id", "164544xxxx");
param.put("nonce_str", WXPayUtil.generateNonceStr());
param.put("body", "企业助力宝套餐购买"+CustomerOrder.getCustomerOrderTransactionNumber());
param.put("out_trade_no", orderCode);
String money = String.valueOf(CustomerOrder.getCustomerOrderPrice()*100);
if (money.indexOf(".") > 0) {
// 去掉多余的0
money = money.replaceAll("0+?$", "");
// 如果最后一位是. 则去掉
money = money.replaceAll("[.]$", "");
}
System.out.println(money);
param.put("total_fee", money);
param.put("spbill_create_ip", "127.0.0.1");
param.put("notify_url", "https://www.zebraxxxx.com.cn/activity/info");
param.put("trade_type", "NATIVE");
System.out.println(param.toString());
//调取微信支付的接口
String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//将map数据转换为xml格式
String xml = WXPayUtil.generateSignedXml(param, "zebrainfo20230809wwwcomcn1xxxxxx");
//创建网络链接
HttpClient httpClient = new HttpClient(url);
httpClient.setXmlParam(xml);
httpClient.setHttps(true);
httpClient.post();
String content = httpClient.getContent();
return WXPayUtil.xmlToMap(content);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
5.编写Controller层调用API
package com.banma.controller.wechatPayController;
import com.banma.entity.CustomerOrder;
import com.banma.util.Result;
import com.banma.wxpay.PayServiceImpl;
import com.banma.wxpay.service.PayService;
import com.github.wxpay.sdk.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/activity")
@CrossOrigin
@Api(tags = "微信支付API")
public class WeChatPayController {
@Autowired
PayService PayService;
@ApiOperation("微信统一收单下单支付接口API")
@PostMapping("/wxPay")
public Result wxPay(@RequestBody CustomerOrder CustomerOrder){
Map<String,Object> map = (Map<String, Object>) PayService.createUrl(CustomerOrder);
Integer code = map.get("code")==null?0:404;
if(code != 0 && code == 404){
return Result.fail("检测到您还未注册企业,请前往企业注册!");
}
System.out.println(map);
return Result.succ("调用成功",map);
}
@RequestMapping("/info")
public String info(HttpServletRequest httpServletRequest){
try {
//读取支付回调数据
InputStream inputStream = httpServletRequest.getInputStream();
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
byte[] bytes=new byte[1024];
int len=0;
while ((len=inputStream.read(bytes))!=-1){
byteArrayOutputStream.write(bytes,0,len);
}
byteArrayOutputStream.close();
inputStream.close();
String res = new String(byteArrayOutputStream.toByteArray(), "UTF-8");
System.out.println(res);
//返回格式必须是这样
Map<String,String> map=new HashMap<>();
map.put("return_code", "SUCCESS");
map.put("return_msg", "OK");
System.out.println("发送成功!");
return WXPayUtil.mapToXml(map);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
调用上面的统一下单接口返回的Url在前端转换为二维码即可实现扫码支付亲测可用!