一步一步的接入微信支付

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);
    }
}
  1. 业务层代码


    /**
     *充值接口的具体实现
     */
    @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;
    }

最后, 大概流程就是这样 支付宝支付的话 流程也是差不多 只是商户平台和开发平台配置的东西不同,抽空闲时间做的一个记录,没有很详细,作为一个初学者可以简单了解下这个过程,谢谢

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值