springboot 小程序微信支付

这篇具有很好参考价值的文章主要介绍了springboot 小程序微信支付。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

看效果

springboot集成微信小程序支付,java,小程序,微信

 

参考文章:SpringBoot + 小程序 整合微信支付和退款 V2版 - 码农教程

本文仅作记录

参考文章: UniApp + SpringBoot 实现微信支付和退款 - 奔跑的砖头 - 博客园

Springboot整合支付宝支付参考: UniApp + SpringBoot 实现支付宝支付和退款 - 奔跑的砖头 - 博客园

一、开发前提

  • 微信支付商户号接入微信支付
  • 商户号绑定对应的小程序
  • 获取对应的 信息
    • 开放平台: appId
    • 商户号: mchId
    • 商户秘钥: mchKey
    • p12证书:
    • apiclient_key.pem证书文件

官方网站: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1

二、Springboot整合微信支付

2.1 导入基本的pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 微信支付坐标 start-->
<dependency>
    <groupId>com.github.binarywang</groupId>
    <artifactId>weixin-java-pay</artifactId>
    <version>4.2.5.B</version>
</dependency>
<!-- 退款用 -->
<dependency>
    <groupId>org.jodd</groupId>
    <artifactId>jodd-http</artifactId>
    <version>6.0.8</version>
</dependency>
<!-- 微信支付坐标 end-->

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

2.2 在 application.yml 中添加配置

回调地址 我这里使用 ngrok内网穿透 官网: ngrok - Online in One Line

# 服务启动端口
server:
  port: 8081

# 微信pay相关
wxpay:
  # appId
  appId: # 自己的appId
  # 商户id
  mchId:  # 自己的商户id
  # 商户秘钥
  mchKey: # 商户秘钥
  # p12证书文件的绝对路径或者以classpath:开头的类路径.
  keyPath: classpath:/wxpay_cert/apiclient_cert.p12
  privateKeyPath: classpath:/wxpay_cert/apiclient_key.pem
  privateCertPath: classpath:/wxpay_cert/apiclient_cert.pem
  # 微信支付的异步通知接口
  # 我这里使用的ngrok内网穿透 
  notifyUrl: https://bfb3-221-237-148-6.ap.ngrok.io/wechat/pay/notify
  # 退款回调地址
  refundNotifyUrl: https://bfb3-221-237-148-6.ap.ngrok.io/wechat/pay/refund_notify

2.3 创建配置文件对应的 配置类

package com.system.system.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties(prefix = "wxpay")
public class WechatPayConfig {
    private String appId;
    private String mchId;
    private String mchKey;
    private String keyPath;
    private String privateKeyPath;
    private String privateCertPath;
    private String notifyUrl;
}

2.4 在service层 创建 BizWechatPayService类

package com.system.system.service.impl;

import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.net.InetAddress;

/**
 * 微信支付
 */
@Service
@ConditionalOnClass(WxPayService.class)
@EnableConfigurationProperties(WechatPayConfig.class)
@AllArgsConstructor
public class BizWechatPayService {

    private WechatPayConfig wechatPayConfig;

    public WxPayService wxPayService() {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(wechatPayConfig.getAppId());
        payConfig.setMchId(wechatPayConfig.getMchId());
        payConfig.setMchKey(wechatPayConfig.getMchKey());
        payConfig.setKeyPath(wechatPayConfig.getKeyPath());
        payConfig.setPrivateKeyPath(wechatPayConfig.getPrivateKeyPath());
        payConfig.setPrivateCertPath(wechatPayConfig.getPrivateCertPath());
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);
        payConfig.setSignType("MD5");

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }

    /**
     * 创建微信支付订单
     *
     * @param productTitle 商品标题
     * @param outTradeNo   订单号
     * @param totalFee     总价
     * @param openId     openId
     * @return
     */
    public Object createOrder(String productTitle, String outTradeNo, Integer totalFee, String openId) {
        try {
            WxPayUnifiedOrderRequest request = new WxPayUnifiedOrderRequest();
            // 支付描述
            request.setBody(productTitle);
            // 订单号
            request.setOutTradeNo(outTradeNo);
            // 请按照分填写
            request.setTotalFee(totalFee);
            // 小程序需要传入 openid
            request.setOpenid(openId);
            // 回调链接
            request.setNotifyUrl(wechatPayConfig.getNotifyUrl());
            // 终端IP.
            request.setSpbillCreateIp(InetAddress.getLocalHost().getHostAddress());
            // 设置类型为JSAPI
            request.setTradeType(WxPayConstants.TradeType.JSAPI);
            // 一定要用 createOrder 不然得自己做二次校验
            Object order = wxPayService().createOrder(request);
            return order;
        } catch (Exception e) {
            return null;
        }

    }

    /**
     * 退款
     *
     * @param tradeNo 订单号
     * @param totalFee 总价
     * @return
     */
    public WxPayRefundResult refund(String tradeNo, Integer totalFee) {
        WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
        wxPayRefundRequest.setTransactionId(tradeNo);
        wxPayRefundRequest.setOutRefundNo(String.valueOf(System.currentTimeMillis()));
        wxPayRefundRequest.setTotalFee(totalFee);
        wxPayRefundRequest.setRefundFee(totalFee);
        wxPayRefundRequest.setNotifyUrl(wechatPayConfig.getRefundNotifyUrl());
        try {
            WxPayRefundResult refund = wxPayService().refundV2(wxPayRefundRequest);
            if (refund.getReturnCode().equals("SUCCESS") && refund.getResultCode().equals("SUCCESS")) {
                return refund;
            }

        } catch (WxPayException e) {
            e.printStackTrace();
        }
        return null;
    }
}

2.5 创建Controller测试

package com.runbrick.paytest.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.runbrick.paytest.util.wxpay.BizWechatPayService;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/wechat/pay")
@AllArgsConstructor
public class WechatController {

    BizWechatPayService wechatPayService;

    private static Logger logger = LoggerFactory.getLogger(WechatController.class);

    /**
     * 创建微信订单
     *
     * @return
     */
    @RequestMapping(value = "/unified/request", method = RequestMethod.GET)
    public Object appPayUnifiedRequest() {
        // totalFee 必须要以分为单位
        Object createOrderResult = wechatPayService.createOrder("测试支付", String.valueOf(System.currentTimeMillis()), 1, "从前端传入的openIdopendId");
        logger.info("统一下单的生成的参数:{}", createOrderResult);
        return createOrderResult;
    }

    @RequestMapping(method = RequestMethod.POST, value = "notify")
    public String notify(@RequestBody String xmlData) {
        try {
            WxPayOrderNotifyResult result = wechatPayService.wxPayService().parseOrderNotifyResult(xmlData);
            // 支付返回信息
            if ("SUCCESS".equals(result.getReturnCode())) {
                // 可以实现自己的业务逻辑
                logger.info("来自微信支付的回调:{}", result);
            }

            return WxPayNotifyResponse.success("成功");
        } catch (WxPayException e) {
            logger.error(e.getMessage());
            return WxPayNotifyResponse.fail("失败");
        }
    }

    /**
     * 退款
     *
     * @param transaction_id
     */
    @RequestMapping(method = RequestMethod.POST, value = "refund")
    public void refund(String transaction_id) {
        // totalFee 必须要以分为单位,退款的价格可以这里只做的全部退款
        WxPayRefundResult refund = wechatPayService.refund(transaction_id, 1);
        // 实现自己的逻辑
        logger.info("退款本地回调:{}", refund);
    }

    /**
     * 退款回调
     *
     * @param xmlData
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "refund_notify")
    public String refundNotify(@RequestBody String xmlData) {
        // 实现自己的逻辑
        logger.info("退款远程回调:{}", xmlData);
        // 必须要返回 SUCCESS 不过有 WxPayNotifyResponse 给整合成了 xml了
        return WxPayNotifyResponse.success("成功");
    }

}

三、前端代码

<template>
    <view class="content">
        <view class="text-area">
            <text class="title">{{title}}</text>
        </view>
        <button type="default" @click="goPay()">点我前去支付</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                title: '跟我去支付'
            }
        },
        onLoad() {

        },
        methods: {
            goPay() {
                uni.request({
                    url: "https://bfb3-221-237-148-6.ap.ngrok.io/wechat/pay/unified/request",
                    success(res) {
                        let obj = {
                            appid: res.data.appId,
                            noncestr: res.data.nonceStr,
                            package: res.data.packageValue,
                            partnerid: res.data.partnerId,
                            prepayid: res.data.prepayId,
                            timestamp: parseInt(res.data.timeStamp),
                            sign: res.data.sign,
                        };

                        uni.requestPayment({
                            provider: "wxpay",
                            orderInfo: obj,
                            success(res) {
                                uni.showModal({
                                    content: "支付成功",
                                    showCancel: false
                                })
                            },
                            fail(e) {
                                uni.showModal({
                                    content: "支付失败,原因为: " + e.errMsg,
                                    showCancel: false
                                })
                            },
                            complete() {
                                console.log("啥也没干");
                            }
                        });

                    }
                })

            }
        }
    }
</script>

<style>
    page {
        background-color: #ff5500;
    }

    .content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .text-area {
        display: flex;
        justify-content: center;
    }

    .title {
        font-size: 36rpx;
        color: #8f8f94;
    }
</style>

待解决的问题

 这段前端是怎么传值的,一直没有解决文章来源地址https://www.toymoban.com/news/detail-743529.html

@RequestMapping(method = RequestMethod.POST, value = "notify")
    public String notify(@RequestBody String xmlData) {
        try {
            WxPayOrderNotifyResult result = wechatPayService.wxPayService().parseOrderNotifyResult(xmlData);
            // 支付返回信息
            if ("SUCCESS".equals(result.getReturnCode())) {
                // 可以实现自己的业务逻辑
                logger.info("来自微信支付的回调:{}", result);
            }

            return WxPayNotifyResponse.success("成功");
        } catch (WxPayException e) {
            logger.error(e.getMessage());
            return WxPayNotifyResponse.fail("失败");
        }
    }

到了这里,关于springboot 小程序微信支付的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • 小程序微信支付V3版本Java集成

    相较于之前的微信支付API,主要区别是: 遵循统一的REST的设计风格 使用JSON作为数据交互的格式,不再使用XML 使用基于非对称密钥的SHA256-RSA的数字签名算法,不再使用MD5或HMAC-SHA256 不再要求携带HTTPS客户端证书(仅需携带证书序列号) 使用AES-256-GCM,对回调中的关键信息进

    2024年02月11日
    浏览(11)
  • 微信小程序完整实现微信支付功能(SpringBoot和小程序)

    微信小程序完整实现微信支付功能(SpringBoot和小程序)

    1.前言 不久前给公司实现支付功能,折腾了一阵子,终于实现了,微信支付对于小白来说真的很困难,特别是没有接触过企业级别开发的大学生更不用说,因此尝试写一篇我如何从小白实现微信小程序支付功能的吧,使用的后端是 SpringBoot 。 2.准备工作 首先,要实现支付功能

    2024年02月04日
    浏览(20)
  • springboot实现微信小程序V3微信支付功能

    appId:小程序appid appSecret:小程序的secret mchId:商户号 keyPath:商户私钥路径(apiclient_key.pem) certPath:证书路径(apiclient_cert.pem) platFormPath:平台证书(cert.pem) 注 : 需要通过写程序生成平台证书(见v3Get()方法) apiKey3:apiv3密钥 serialnumber:商户证书序列号 notifyUrl:回调地

    2024年02月12日
    浏览(56)
  • 【微信支付】java-微信小程序支付-V3接口

    【微信支付】java-微信小程序支付-V3接口

    最开始需要在微信支付的官网注册一个商户; 在管理页面中申请关联小程序,通过小程序的 appid 进行关联;商户号和appid之间是多对多的关系 进入微信公众平台,功能-微信支付中确认关联 具体流程请浏览官方文档:接入前准备-小程序支付 | 微信支付商户平台文档中心 流程走

    2024年02月06日
    浏览(21)
  • springboot整合IJPay实现微信支付-V3---微信小程序

    springboot整合IJPay实现微信支付-V3---微信小程序

    微信支付适用于许多场合,如小程序、网页支付、但微信支付相对于其他支付方式略显麻烦,我们使用IJpay框架进行整合 JPay 让支付触手可及, 封装了微信支付、支付宝支付、银联支付常用的支付方式以及各种常用的接口。不依赖任何第三方 mvc 框架,仅仅作为工具使用简单

    2024年02月02日
    浏览(36)
  • SpringBoot对接微信小程序支付功能开发(一,下单功能)

    1,接入前准备: 接入模式选择直连模式; 申请小程序,得到APPID,并开通微信支付; 申请微信商户号,得到mchid,并绑定APPID; 配置商户API key,下载并配置商户证书,根据微信官方文档操作:https://pay.weixin.qq.com/wiki/doc/apiv3/open/pay/chapter2_8_1.shtml 上面都配置完之后会得到:小

    2024年02月10日
    浏览(22)
  • 微信小程序支付-java对接微信

     一共是两个方法: 一个方法后台生成预支付订单,得到预支付交易会话标识prepay_id,传给前端,让前端调起小程序支付; 一个是支付回调 目录 一、生成预支付订单  注意: 二、 支付回调         封装参数向微信发送生成预支付交易单请求,微信会返回一个prepay_id,再将

    2024年02月12日
    浏览(14)
  • 【Java】微信小程序V3支付(后台)

    【Java】微信小程序V3支付(后台)

    目录         相关官网文档         1.需要的参数         2.引入库         3.用到的工具类         4.支付下单实现         5.支付回调 接入前准备-小程序支付 | 微信支付商户平台文档中心 微信支付-JSAPI下单 获取平台证书列表-文档中心-微信支付商户平

    2024年02月12日
    浏览(33)
  • Java实现微信小程序V3支付

    Java实现微信小程序V3支付

    2024年02月12日
    浏览(20)
  • 【微信小程序】Java实现微信支付(小程序支付JSAPI-V3)java-sdk工具包

    【微信小程序】Java实现微信支付(小程序支付JSAPI-V3)java-sdk工具包

          对于一个没有写过支付的小白,打开微信支付官方文档时彻底懵逼 ,因为 微信支付文档太过详细, 导致我无从下手,所以写此文章,帮助第一次写支付的小伙伴梳理一下。 一、流程分为三个接口:(这是前言,先看一遍,保持印象,方便理解代码) 1、第一个接口:

    2024年02月03日
    浏览(16)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包