欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java后端PayPal支付实现教程

程序员文章站 2022-06-18 10:03:20
首先引入 paypal的sdk 这里我引入的是1.0.4版本的 ...

首先引入 paypal的sdk 这里我引入的是1.0.4版本的

            <!-- 贝宝支付  sdk   -->
            <dependency>
                <groupid>com.paypal.sdk</groupid>
                <artifactid>checkout-sdk</artifactid>
                <paypal-sdk.version>1.0.4</paypal-sdk.version>
            </dependency>

yml文件引入公司在官网的相关配置

这里我做了yml的文件环境隔离,限免的配置做了示例

  #  贝宝支付的测试服
pay:  
  paypal:
    clientid: aeex1pnmnap3ruv8jtbmznahs_goffwlog6sg3tiqh1_mbj0
    clientsecret: emdda7g_q7kmoih08qjfg-dab8d2thkytzrr
    #测试的mode
    mode: sandbox
    #正式的mode
    mode: live
/**
 * @author majun
 * @email majun6534@dingtalk.com
 * @date 2021/7/29
 * @since 2.0.0
 */
@data
@allargsconstructor
@noargsconstructor
@apimodel
public class paypalvo extends requestmodel {
    /**  本站订单号 */
    @apimodelproperty(value = "本站订单号")
    private string orderno;

    /**  三方订单号 */
    @apimodelproperty(value = "本站订单号")
    private string outorderno;

    /** 1 书币充值 ; 2 plus会员充值;3 premium会员充值 */
    @apimodelproperty(value = "1 书币充值 ; 2 plus会员充值;3 premium会员充值")
    private integer ordertype;
}

paypal支付

    /**
     * 贝宝支付
     *
     * @param paypalvo 请求对象
     * @return 返回结果
     */
    @postmapping("/paypalnotify")
    @apioperation(value = "贝宝支付二次验证")
    @deprecated
    public responsemodel<payorderdto> paypalnotify(@requestbody paypalvo paypalvo){
        if (objectutils.isempty(paypalvo.getorderno()) || objectutils.isempty(paypalvo.getoutorderno()) || objectutils.isempty(paypalvo.getordertype())){
            return responsemodel.error(appconfigstatuscodeservice.getstatuscode(paypalvo.getlanguage(), responsecnsate.param_exception));
        }
        // 根据paypal的订单id,捕获订单付款
        string outorderno = paypalvo.getoutorderno();
        string orderno = paypalvo.getorderno();
        integer ordertype = paypalvo.getordertype();
        // 校验该订单是否处理
        if (payorderservice.isdispose(orderno) == payconstants.order_is_dispose) {
            return responsemodel.error(appconfigstatuscodeservice.getstatuscode(paypalvo.getlanguage(), responsecnsate.order_processed));
        }
        //进行二次验证
        boolean pay = paypalutils.verifyorderinfo(outorderno);
        //如果成功则执行后面的逻辑
        if (pay){
            boolean b = orderservice.finishorder(orderno, ordertype,paypalvo.getlanguage());
            if (!b){
                return responsemodel.error(appconfigstatuscodeservice.getstatuscode(paypalvo.getlanguage(), responsecnsate.order_handler_fail));
            }
            //保存订单号返回订单信息
            payorderdto payorderdto =orderservice.saveandgetorderinfo(paypalvo.getuserid(),outorderno,orderno);
            if (objectutils.isnotempty(payorderdto)){
                return responsemodel.success(payorderdto);
            }
            return responsemodel.error(appconfigstatuscodeservice.getstatuscode(paypalvo.getlanguage(), responsecnsate.return_order_info_fail));
        }
        //失败返回提示
        return responsemodel.error(appconfigstatuscodeservice.getstatuscode(paypalvo.getlanguage(), responsecnsate.auth_fail_two));
    }

后面为了让大家都看的明白 我单独抽取了一个工具,简单的做了描述

package com.wyzz.global.untils.paypal;

import com.baomidou.mybatisplus.core.toolkit.objectutils;

import com.paypal.core.paypalenvironment;
import com.paypal.core.paypalhttpclient;
import com.paypal.http.httpresponse;
import com.paypal.http.serializer.json;
import com.paypal.orders.*;
import com.paypal.payments.capturesgetrequest;
import lombok.extern.slf4j.slf4j;
import java.io.ioexception;
import java.util.hashmap;
import java.util.list;
import java.util.map;

import org.json.jsonobject;
import org.springframework.beans.factory.annotation.value;
import org.springframework.stereotype.service;

/**
 * paypal工具类
 *
 * @author majun
 * @email majun6534@dingtalk.com
 * @date 2021/7/29
 * @since 2.0.0
 */
@service
@slf4j
public class paypalutils {

    /**
     * paypal配置应用的客户端id
     */
    @value("${pay.paypal.clientid}")
    private string clientid;

    /**
     * paypal配置应用的客户端密钥
     */
    @value("${pay.paypal.clientsecret}")
    private string clientsecret;

    /**
     * paypal连接环境:live表示生产,sandbox表示沙盒
     */
    @value("${pay.paypal.mode}")
    private string mode;

    /**
     * paypal的http客户端
     * @param mode 环境信息
     * @param clientid 客户端id
     * @param clientsecret 密钥
     * @return
     */
    public paypalhttpclient client(string mode, string clientid, string clientsecret) {
        log.info("mode={}, clientid={}, clientsecret={}", mode, clientid, clientsecret);
        paypalenvironment environment = mode.equals("live") ? new paypalenvironment.live(clientid, clientsecret) : new paypalenvironment.sandbox(clientid, clientsecret);
        return new paypalhttpclient(environment);
    }

    /**
     * 构建订单请求体
     * @return
     */
    public orderrequest buildrequestbody() {
        return new orderrequest();
    }

    /**
     * 校验订单信息:先扣款,后查询订单详情
     * @param orderid 前端提供的palpay的订单id
     * @return 订单存在并已扣款成功返回true
     */
    public boolean verifyorderinfo(string orderid) {
        boolean f = false;
        try {
            // 1.用户授权支付成功,进行扣款操作
            this.captureorder(orderid);
        } catch (exception e) {
            e.printstacktrace();
        } finally {
            // 2.扣款操作失败时也要查询订单,确认是否已扣款
            try {
                ordersgetrequest request = new ordersgetrequest(orderid);
                httpresponse<order> response = client(mode, clientid, clientsecret).execute(request);
                system.out.println("status code: " + response.statuscode());
                system.out.println("status: " + response.result().status());
                system.out.println("order id: " + response.result().id());
                if(response.result().purchaseunits().get(0).payments() != null) {
                    list<capture> captures = response.result().purchaseunits().get(0).payments().captures();
                    if(captures != null) {
                        for (capture capture : captures) {
                            if (capture.id() != null && capture.id().length() > 0) {
                                f = true;
                            }
                        }
                    }
                }
            } catch (exception e2) {
                e2.printstacktrace();
            }
        }
        return f;
    }

    /**
     * 用户授权支付成功,进行扣款操作:
     * 用户通过createorder生成 approveurl 跳转paypal支付成功后,只是授权,并没有将用户的钱打入我们的paypal账户,我们需要通过 captureorder接口,将钱打入我的paypal账户
     * @param orderid 前端提供的palpay的订单id
     */
    public void captureorder(string orderid){
        orderscapturerequest request = new orderscapturerequest(orderid);
        request.requestbody(this.buildrequestbody());
        httpresponse<order> response = null;
        try {
            response = client(mode, clientid, clientsecret).execute(request);
        } catch (ioexception e1) {
            try {
                log.error("第1次调用paypal扣款失败");
                response = client(mode, clientid, clientsecret).execute(request);
            } catch (exception e) {
                try {
                    log.error("第2次调用paypal扣款失败");
                    response = client(mode, clientid, clientsecret).execute(request);
                } catch (exception e2) {
                    log.error("第3次调用paypal扣款失败,失败原因 {}", e2.getmessage() );
                }
            }
        }
        if (objectutils.isnotempty(response)) {
            log.info("status code = {}, status = {}, orderid = {}", response.statuscode(), response.result().status(), response.result().id());
            for (linkdescription link : response.result().links()) {
                log.info("links-{}: {}    \tcall type: {}", link.rel(), link.href(), link.method());
            }
            for (purchaseunit purchaseunit : response.result().purchaseunits()) {
                for (capture capture : purchaseunit.payments().captures()) {
                    log.info("capture id: {}", capture.id());
                    log.info("status: {}", capture.status());
                    log.info("invoice_id: {}", capture.invoiceid());
                    if("completed".equals(capture.status())) {
                        //进行数据库操作,修改订单状态为已支付成功,尽快发货(配合回调和capturesget查询确定成功)
                        log.info("支付成功,状态为=completed");
                    }
                    if("pending".equals(capture.status())) {
                        log.info("status_details: {}", capture.capturestatusdetails().reason());
                        string reason = "pending";
                        if(capture.capturestatusdetails() != null && capture.capturestatusdetails().reason() != null) {
                            reason = capture.capturestatusdetails().reason();
                        }
                        //进行数据库操作,修改订单状态为已支付成功,但触发了人工审核,请审核通过后再发货(配合回调和capturesget查询确定成功)
                        log.info("支付成功,状态为=pending : {}", reason);
                    }
                }
            }
            payer buyer = response.result().payer();
            log.info("buyer email address: {}", buyer.email());
            log.info("buyer name: {} {}", buyer.name().givenname(), buyer.name().surname());
        }
    }

    /**
     * 查询订单详情
     * @param orderid 前端提供的palpay的订单id
     * @throws ioexception
     */
    public void ordersgetrequest(string orderid) throws ioexception {
        ordersgetrequest request = new ordersgetrequest(orderid);
        httpresponse<order> response = null;
        try {
            response = client(mode, clientid, clientsecret).execute(request);
        } catch (exception e) {
            try {
                system.out.println("调用paypal订单查询失败,链接异常1");
                response = client(mode, clientid, clientsecret).execute(request);
            } catch (exception e2) {
                try {
                    system.out.println("调用paypal订单查询失败,链接异常2");
                    response = client(mode, clientid, clientsecret).execute(request);
                } catch (exception e3) {
                    system.out.println("调用paypal订单查询失败,链接异常3");
                    system.out.println(e3.getmessage());
                }
            }
        }
        system.out.println("status code: " + response.statuscode());
        system.out.println("status: " + response.result().status());
        system.out.println("order id: " + response.result().id());
        if(response.result().purchaseunits().get(0).payments() != null) {
            list<capture> captures = response.result().purchaseunits().get(0).payments().captures();
            if(captures != null) {
                for (capture capture : captures) {
                    system.out.println("\t订单编号= " + capture.invoiceid() + "\tcapture id= " + capture.id() + "\tcapture status= " + capture.status() + "\tcapture amount= " + capture.amount().currencycode() + ":" + capture.amount().value());
                }
            }
            list<refund> refunds = response.result().purchaseunits().get(0).payments().refunds();
            if(refunds != null) {
                for (refund refund : refunds) {
                    system.out.println("\t售后编号= " + refund.invoiceid() + "\trefund id= " + refund.id() + "\trefund status= " + refund.status() + "\trefund amount= " + refund.amount().currencycode() + ":" + refund.amount().value());
                }
            }
        }
        system.out.println("links: ");
        for (linkdescription link : response.result().links()) {
            system.out.println("\t" + link.rel() + ": " + link.href() + "\tcall type: " + link.method());
        }
    }

    /**
     * 查询扣款详情
     * @param orderid 前端提供的palpay的订单id
     * @throws ioexception
     */
    public void capturesgetrequest(string orderid) throws ioexception {
        capturesgetrequest request = new capturesgetrequest(orderid);
        httpresponse<com.paypal.payments.capture> response = client(mode, clientid, clientsecret).execute(request);
        system.out.println("status code: " + response.statuscode());
        system.out.println("status: " + response.result().status());
        system.out.println("capture ids: " + response.result().id());
        system.out.println("links: ");
        for (com.paypal.payments.linkdescription link : response.result().links()) {
            system.out.println("\t" + link.rel() + ": " + link.href() + "\tcall type: " + link.method());
        }
    }

    public map<string,object> createorder(orderrequest orderrequest) {
        orderscreaterequest request = new orderscreaterequest();
        request.header("prefer","return=representation");
        request.requestbody(orderrequest);
//        paypalclient paypalclient = new paypalclient();
        httpresponse<order> response = null;
        try {
            response = client(mode, clientid, clientsecret).execute(request);
        } catch (ioexception e1) {
            try {
                log.error("第1次调用paypal订单创建失败");
                response = client(mode, clientid, clientsecret).execute(request);
            } catch (exception e) {
                try {
                    log.error("第2次调用paypal订单创建失败");
                    response = client(mode, clientid, clientsecret).execute(request);
                } catch (exception e2) {
                    log.error("第3次调用paypal订单创建失败,失败原因:{}", e2.getmessage());
                }
            }
        }
//        string approve = "";
        map<string,object> map = new hashmap();
        if (response.statuscode() == 201) {
            log.info("status code = {}, status = {}, orderid = {}, intent = {}", response.statuscode(), response.result().status(), response.result().id(), response.result().checkoutpaymentintent());
            map.put("id",response.result().id());
            for (linkdescription link : response.result().links()) {
                log.info("links-{}: {}    \tcall type: {}", link.rel(), link.href(), link.method());
                if(link.rel().equals("approve")) {
//                    approve = link.href();
                    map.put("outorderno",link.href());

                }
            }
            string totalamount = response.result().purchaseunits().get(0).amountwithbreakdown().currencycode() + ":" + response.result().purchaseunits().get(0).amountwithbreakdown().value();
            log.info("total amount: {}", totalamount);
//            string json= new jsonobject(new json().serialize(response.result())).tostring(4);
//            log.info("createorder response body: {}", json);
        }
        return map;
    }

//    public static void main(string[] args) throws exception {
//        paypalutils paypalutils = new paypalutils();
//        paypalutils.verifyorderinfo("45s82276s8854414k");
//        paypalutils.ordersgetrequest("45s82276s8854414k");
//        paypalutils.captureorder("18k07174px6483500");
//        paypalutils.capturesgetrequest("31v65486wc667442g");
//        // issue : order_already_captured 订单已被捕获
//        // intent=capture 每个订单只允许捕获一次
//    }
}

不敢说描述的有多么到位 只希望给java将要对接paypal的同学一点儿参考

到此这篇关于java后端paypal支付实现教程的文章就介绍到这了,更多相关java paypal支付内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!