微信支付:Native支付 工具类



import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.core.exception.ServiceException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.payments.model.Transaction;
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.Amount;
import com.wechat.pay.java.service.payments.nativepay.model.*;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.*;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;

/**
 * Native 支付工具类  获取支付地址、解析支付数据
 *
 * @Author: szl
 * @Date: 2024年1月18日 下午15:30:11
 */
@Slf4j
public class PayUtils {
    //商户号
    public static String mchid = "1604711111";
    //商户API私钥路径
    //生产:
    //public static String privateKeyPath = "/hom123/apiclient_key.pem";
    //商户证书序列号
    public static String merchantSerialNumber = "543BA";
    //商户APIV3密钥
    public static String apiV3key = "iK81144423";
    public static String appId = "wx0a281111f7e";
    //退款后的回调地址
    public static final String refundNotifyUrl = "http://47.1711457/pay/refundNotify";
    //支付后的回调地址
    public static final String nativeNotifyUrl = "htt27/pay/notifyNative";

    // 使用自动更新平台证书的RSA配置
    public static Config config = new RSAAutoCertificateConfig.Builder()
            .merchantId(mchid) // 商户号
            .privateKeyFromPath(privateKeyPath)  // API证书地址(此处的路径自己调试一下,能找到就行)
            .merchantSerialNumber(merchantSerialNumber) // API证书序列号
            .apiV3Key(apiV3key) // API密匙
            .build();
    // 初始化 解析器 NotificationParser
    public static NotificationParser parser = new NotificationParser((NotificationConfig) config);
    // 构建支付、查询的service
    public static NativePayService nativePayService = new NativePayService.Builder().config(config).build();
    // 构建退款的service
    public static RefundService refundService = new RefundService.Builder().config(config).build();

    /**
     * 支付解析,解析成订单数据
     */
    public static Transaction parserTransaction(HttpServletRequest request) {
        RequestParam requestParam = parseRequest(request);
        // 解析为 Transaction 对象(解密数据) 解密完成后的数据
        Transaction transaction = parser.parse(requestParam, Transaction.class);
        return transaction;
    }

    /**
     * 退款解析,解析成退款单
     */
    public static RefundNotification parserRefundNotification(HttpServletRequest request) throws Exception {
        RequestParam requestParam = parseRequest(request);
        RefundNotification refundNotification = parser.parse(requestParam, RefundNotification.class);
        return refundNotification;
    }

    public static RequestParam parseRequest(HttpServletRequest request) {
        try {
            // 获取请求体原内容(此时获取的数据是加密的)
            BufferedReader reader = request.getReader();
            StringBuilder requestBody = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }
            // 获取请求携带的数据,构造参数
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(request.getHeader("Wechatpay-Serial")) // 微信支付平台证书的序列号
                    .nonce(request.getHeader("Wechatpay-Nonce")) // 签名中的随机数
                    .signature(request.getHeader("Wechatpay-Signature"))  // 应答的微信支付签名
                    .timestamp(request.getHeader("Wechatpay-Timestamp")) // 签名中的时间戳
                    .body(requestBody.toString()) // 请求体内容(原始内容,不要解析)
                    .build();
            //解密完成后的数据
            return requestParam;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析失败:{}", e.getMessage());
            return null;
        }
    }

    /**
     * 获取支付地址 设置回调路径
     *
     * @param total     【总金额】 订单总金额,单位为分
     * @param desc      商品描述
     * @param notifyUrl 回调地址(必须是http)   如:"http://47.92.***.2**:80*7/pay/notifyNative"
     * @return
     * @Param orderNo 自己后端的唯一订单号
     */
    public static String nativePayAddr(Integer total, String desc, String notifyUrl, String orderNo, String attach) {
        try {
            PrepayRequest request = new PrepayRequest();
            Amount amount = new Amount();
            amount.setTotal(total); // 【总金额】 订单总金额,单位为分。
            request.setAmount(amount);
            request.setAppid(appId); // 应用ID
            request.setMchid(mchid);  // 商户号
            request.setDescription(desc);  // 商品描述
            request.setNotifyUrl(notifyUrl);  // 支付成功的回调地址 "http://47.92.132.209:8027/pay/notifyNative"
            request.setAttach(attach);
            request.setOutTradeNo(orderNo);  // 自己后端的唯一订单号,此处使用时间模拟
            // 调用下单方法,得到应答,发送请求
            PrepayResponse response = nativePayService.prepay(request);
            // 使用微信扫描 code_url 对应的二维码,即可体验Native支付
            log.info("支付地址:{}", response.getCodeUrl());
            return response.getCodeUrl();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("获取支付的url失败:" + e.getMessage());
            return "获取支付的地址失败";
        }
    }

    /**
     * 手动根据微信订单号查询订单
     *
     * @throws Exception
     */
    public static Transaction queryOrderById(String transactionId) {
        try {
            QueryOrderByIdRequest queryRequest = new QueryOrderByIdRequest();
            queryRequest.setMchid(mchid);
            queryRequest.setTransactionId(transactionId);
            Transaction result = nativePayService.queryOrderById(queryRequest);
            log.info("订单状态: {}", result.getTradeState());
            return result;
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.printf("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
            System.out.printf("reponse body=[%s]\n", e.getResponseBody());
            return null;
        }
    }

    /**
     * 手动根据 商 户 订单号查询订单
     *
     * @throws Exception
     */
    public static Transaction queryOutTradeNoByOrderNO(String outTradeNo) {
        try {
            QueryOrderByOutTradeNoRequest queryRequest = new QueryOrderByOutTradeNoRequest();
            queryRequest.setMchid(mchid);
            queryRequest.setOutTradeNo(outTradeNo);
            Transaction transaction = nativePayService.queryOrderByOutTradeNo(queryRequest);
            log.info("订单状态: {}", transaction);
            return transaction;
        } catch (ServiceException e) {
            e.printStackTrace();
            log.info("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
            log.info("reponse body=[%s]\n", e.getResponseBody());
            return null;
        }
    }

    /**
     * 根据商户订单号进行退款申请
     *
     * @param refundNo
     * @param refuntMoney
     * @param orderTotal
     * @throws Exception
     */
    public static Refund refundByNo(String refundNo, Long refuntMoney, Long orderTotal) {
        try {
            CreateRequest request = new CreateRequest();
            AmountReq amountReq = new AmountReq();
            //退款金额
            amountReq.setRefund(refuntMoney);
            //原订单金额
            amountReq.setTotal(orderTotal);
            //货币类型(默认人民币)
            amountReq.setCurrency("CNY");
            request.setAmount(amountReq);
            //商户单号 微信支付订单号 二选一
            //request.setTransactionId("");
            request.setOutTradeNo(refundNo);
            //商户退款单号
            request.setOutRefundNo(refundNo);
            request.setNotifyUrl(refundNotifyUrl);
            Refund refundOrder = refundService.create(request);
            log.info("退款订单: {}", refundOrder.toString());
            log.info("订单状态:{}", refundOrder.getStatus(), refundOrder.toString());
            return refundOrder;
        } catch (ServiceException e) {
            e.printStackTrace();
            // API返回失败, 例如ORDER_NOT_EXISTS
            log.info("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
            log.info("reponse body=[%s]\n", e.getResponseBody());
            return null;
        }
    }

    /**
     * 查询退款
     *
     * @throws Exception
     */
    public static Refund queryByOutRefundNo(String outTradeNo) {
        try {
            QueryByOutRefundNoRequest request = new QueryByOutRefundNoRequest();
            request.setOutRefundNo(outTradeNo);
            Refund refund = refundService.queryByOutRefundNo(request);
            log.info("订单状态: {}", refund);
            return refund;
        } catch (ServiceException e) {
            e.printStackTrace();
            // API返回失败, 例如ORDER_NOT_EXISTS
            log.info("code=[%s], message=[%s]\n", e.getErrorCode(), e.getErrorMessage());
            log.info("reponse body=[%s]\n", e.getResponseBody());
            return null;
        }
    }
}
<!--微信支付依赖-->
        <dependency>
            <groupId>com.github.wechatpay-apiv3</groupId>
            <artifactId>wechatpay-java</artifactId>
            <version>0.2.5</version>
        </dependency>

把工具类中各种key  路径 等关键信息换成自己的就可以用了,记得做好日志和订单

建议:

1、拉起支付时,创建订单。支付成功后被回调时,修改订单

2、申请退款时,创建退款单。退款成功后被回调时,修改退款单 并且修改自己的订单

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PHP微信支付Native支付是指在PHP开发环境中使用微信支付的一种支付方式。具体而言,Native支付是将微信支付的功能集成到PHP程序中,使得用户在网页上能够通过微信扫码支付的方式完成支付流程。 要实现PHP微信支付Native支付,在开发环境中需要先进行以下几个步骤: 1. 注册微信支付商户账号:通过微信支付官方网站注册并获取商户号以及相关的API密钥。 2. 配置服务器环境:搭建PHP开发环境,并确保服务器支持HTTPS协议,因为微信支付要求使用HTTPS进行数据传输。 3. 引入微信支付SDK:下载并引入微信支付的PHP SDK,该SDK提供了调用微信支付接口的相关函数库。 4. 编写支付代码:根据具体需求,编写PHP代码调用微信支付接口,包括生成支付二维码、处理支付结果等。 5. 测试支付流程:在开发环境中进行支付流程的测试,包括生成支付二维码供用户扫码、接收微信支付异步通知等。 需要注意的是,使用微信支付Native支付时,要确保生成的支付二维码能够正常显示,并能够通过微信扫码完成支付。另外,在接收微信支付异步通知时,要对收到的订单信息进行验证,确保支付结果的准确性。 总结来说,PHP微信支付Native支付是在PHP开发环境中实现微信支付功能的一种方式,通过生成支付二维码让用户扫码完成支付流程。要实现该功能,需要注册商户账号、配置服务器环境、引入微信支付SDK并编写相应的支付代码。最后,在开发环境中进行测试,确保支付流程的稳定性和安全性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值