1.首先在微信开放平台创建好 相应的应用
创建完成提交需要审核,审核通过后,如下图:
审核后 需在微信支付里面配置一下关联的 微信商户,
2 .在微信商户平台绑定 刚刚审核的产品.
3. 微信支付的配置类
import com.github.wxpay.sdk.WXPayConfig;
import lombok.SneakyThrows;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.io.InputStream;
@Configuration
@Component
@ConfigurationProperties
public class WeiXinPayConfig implements WXPayConfig {
//商户应用appId
private String appID = "";
//商户ID
private String mchID = "";
//商户key:api秘钥(32位)
private String key = "";
private String certPath = "";
private int httpConnectTimeoutMs = 8000;
private int httpReadTimeoutMs = 10000;
//回调接口
private String payNotifyUrl = "";
@SneakyThrows
@Override
public InputStream getCertStream() {
return this.getClass().getResourceAsStream(certPath);
}
@Override
public String getAppID() {
return appID;
}
public void setAppID(String appID) {
this.appID = appID;
}
@Override
public String getMchID() {
return mchID;
}
public void setMchID(String mchID) {
this.mchID = mchID;
}
@Override
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getCertPath() {
return certPath;
}
public void setCertPath(String certPath) {
this.certPath = certPath;
}
@Override
public int getHttpConnectTimeoutMs() {
return httpConnectTimeoutMs;
}
public void setHttpConnectTimeoutMs(int httpConnectTimeoutMs) {
this.httpConnectTimeoutMs = httpConnectTimeoutMs;
}
@Override
public int getHttpReadTimeoutMs() {
return httpReadTimeoutMs;
}
public void setHttpReadTimeoutMs(int httpReadTimeoutMs) {
this.httpReadTimeoutMs = httpReadTimeoutMs;
}
}
其中key的申请路径同样在商户平台中:
4.微信支付controller代码
@RequestMapping(value = "/xxx",method = RequestMethod.POST)
@ResponseBody
@Transactional
public 返回值(任意,就是普通的接口的返回值) xxx(方法名)(@RequestParam("参数1") Integer 参数1,@RequestParam("参数2") String 参数2,@RequestParam("参数3") String 参数3) throws BusinessException {
// 叭叭叭一堆验证数据 入参啊 查看充值是否开放啊
//封装好一个model类进service层准备调微信的支付接口了
//tradeModel 就是我封装的model 类
Map map= weiXinPayService.方法名(tradeModel);
return CommonReturnType.create("200", "success", map);
//CommonReturnType.create 这个是公司封装的返回model而已
}
//微信支付的回调地址很重要 一般业务代码都在这里面开始实现
//该接口的地址 需要在WeiXinPayConfig 配置好
@RequestMapping(value = "/地址",method = RequestMethod.POST)
@ResponseBody
public CommonReturnType 方法名(){
log.info("------------------开始微信手机支付回调通知--------------------");
InputStream is = null;
String xmlBack = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
try {
is = request.getInputStream();
// 将InputStream转换成String
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
//这里去service层处理具体业务
xmlBack = weiXinPayService.方法名(sb.toString());
} catch (Exception e) {
log.error("-----------------------微信手机支付回调通知失败:", e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return CommonReturnType.create(xmlBack);
}
}
- 业务层代码
/**
*充值接口的具体实现
*/
@Override
@Transactional
public Map 方法名(TradeModel tradeModel) throws BusinessException {
// 咔咔咔一顿检验操作啥的 根据自己的业务需求来
SortedMap<String, String> parameters = new TreeMap<>();
Map<String, String> responseMap = new HashMap<>();
Map<String, String> requestMap = new HashMap<>();
try {
WXPay wxPay = new WXPay(weiXinPayConfig);
parameters.put("body", tradeModel.getTradeDescribe()); // 商品描述
parameters.put("notify_url", weiXinPayConfig.getPayNotifyUrlVIP()); // 接收微信支付异步通知回调地址
parameters.put("out_trade_no", tradeModel.getId()); // 商户订单号
//parameters.put("spbill_create_ip", OtherUtils.getIpAddr(httpServletRequest)); // 终端IP
// parameters.put("total_fee", tradeModel.getPrice().setScale(2, RoundingMode.HALF_UP).intValue() * 100 + ""); // 总金额
parameters.put("total_fee", StringUtil.getMoney(String.valueOf(tradeModel.getPrice()))); // 总金额
//parameters.put("total_fee", StringUtil.getMoney("0.01")); // 总金额
parameters.put("trade_type", "APP");
//这一行就是真正去支付了
Map<String, String> resultMap = wxPay.unifiedOrder(parameters);
//获取返回码
String returnCode = resultMap.get("return_code");
String returnMsg = resultMap.get("return_msg");
log.info("微信支付统一下单 " + returnCode + ":" + returnMsg + "spbill_create_ip" + parameters.get("spbill_create_ip"));
//若返回码为SUCCESS,则会返回一个result_code,再对该result_code进行判断
if ("SUCCESS".equals(returnCode)) {
String resultCode = resultMap.get("result_code");
//String errCodeDes = resultMap.get("err_code_des");
if ("SUCCESS".equals(resultCode)) {
responseMap = resultMap;
}
}
if (responseMap == null || responseMap.isEmpty()) {
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "获取预支付交易会话标识失败");
}
//咔咔咔支付完成后的一顿操作 一般就是存一下 订单号 检测一下订单状态什么的
// 3、签名生成算法
long time = System.currentTimeMillis() / 1000;
String timestamp = Long.toString(time);
requestMap.put("appid", weiXinPayConfig.getAppID());
requestMap.put("partnerid", weiXinPayConfig.getMchID());
requestMap.put("prepayid", responseMap.get("prepay_id"));
requestMap.put("noncestr", responseMap.get("nonce_str"));
requestMap.put("timestamp", timestamp);
requestMap.put("package", "Sign=WXPay");
requestMap.put("sign", WXPayUtil.generateSignature(requestMap, weiXinPayConfig.getKey()));//微信支付签名
return requestMap;
} catch (Exception e) {
log.error("订单号:{},错误信息:{}", tradeModel.getId(), e.getMessage());
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "微信支付统一下单失败");
}
}
@Override
@Transactional
public String notify(String notifyStr) {
String xmlBack = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[报文为空]]></return_msg></xml> ";
try {
// 转换成map
Map<String, String> resultMap = WXPayUtil.xmlToMap(notifyStr);
WeiXinPayConfig weiXinPayConfig = new WeiXinPayConfig();
WXPay wxpayApp = new WXPay(weiXinPayConfig);
if (wxpayApp.isPayResultNotifySignatureValid(resultMap)) {
String returnCode = resultMap.get("return_code"); //状态
String outTradeNo = resultMap.get("out_trade_no");//商户订单号
String transactionId = resultMap.get("transaction_id");
if (returnCode.equals("SUCCESS")) {
if (StringUtils.isNotBlank(outTradeNo)) {
log.info("订单创交易成功" + outTradeNo);
//业务处理,主要是更新订单状态
//更新用户充钱后该有的数据
}
log.info("微信手机支付回调成功,订单号:{}", outTradeNo);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return xmlBack;
}
最后, 大概流程就是这样 支付宝支付的话 流程也是差不多 只是商户平台和开发平台配置的东西不同,抽空闲时间做的一个记录,没有很详细,作为一个初学者可以简单了解下这个过程,谢谢