首先引入 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: aeex1pnmn溴水颜色ap3ruv8jtbmznahs_goffwlog6sg3tiqh1_mbj0 clientcret: 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@apimodelpublic 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 responmodel<payorderdto> paypalnotify(@requestbody paypalvo paypalvo){ if (objectutils.impty(paypalvo.getorderno()) || objectutils.impty(paypalvo.getoutorderno()) || objectutils.impty(paypalvo.getordertype())){ return responmodel.error(appconfigstatuscodervice.getstatuscode(paypalvo.getlanguage(), responcnsate.param_exception)); } // 根据paypal的订单id,捕获订单付款 string outorderno = paypalvo.getoutorderno(); string orderno = paypalvo.getorderno(); integer ordertype = paypalvo.getordertype(); // 校验该订单是否处理 if (payorderrvice.isdispo(orderno) == payconstants.order_is_dispo) { return responmodel.error(appconfigstatuscodervice.getstatuscode(paypalvo.getlanguage(), responcnsate.order_procesd)); } //进行二次验证 boolean pay = paypalutils.verifyorderinfo(outorderno); //如果成功则执行后面的逻辑 if (pay){ boolean b = orderrvice.finishorder(orderno, ordertype,paypalvo.getlanguage()); if (!b){ return responmodel.error(appconfigstatuscodervice.getstatuscode(paypalvo.getlanguage(), responcnsate.order_handler_fail)); } //保存订单号返回订单信息 payorderdto payorderdto =orderrvice.saveandgetorderinfo(paypalvo.geturid(),outorderno,orderno); if (objectutils.isnotempty(payorderdto)){ return responmodel.success(payorderdto); } return responmodel.error(appconfigstatuscodervice.getstatuscode(paypalvo.getlanguage(), responcnsate.return_order_info_fail)); } //失败返回提示 return responmodel.error(appconfigstatuscodervice.getstatuscode(paypalvo.getlanguage(), responcnsate.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.httprespon;import com.paypal.http.rializer.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.rvice;/*** paypal工具类** @author majun* @email majun6534@dingtalk.com* @date 2021/7/29* @since 2.0.0*/@rvice@slf4jpublic class paypalutils {/*** paypal配置应用的客户端id*/@value("${pay.paypal.clientid}")private string clientid;/*** paypal配置应用的客户端密钥*/@value("${pay.paypal.clientcret}")private string clientcret;/*** paypal连接环境:live表示生产,sandbox表示沙盒*/@value("${pay.paypal.mode}")private string mode;/*** paypal的http客户端* @param mode 环境信息* @param clientid 客户端id* @param clientcret 密钥* @return*/public paypalhttpclient client(string mode, string clientid, string clientcret) {log.info("mode={}, clientid={}, clientcret={}", mode, clientid, clientcret);paypalenvironment environment = mode.equals("live") ? new paypalenvironment.live(clientid, clientcret) : new paypalenvironment.sandbox(clientid, clientcret);return new paypalhttpclient(environment);}/*** 构建订单请求体* @return*/public orderrequest buildrequestbo数学cos公式dy() {return new orderrequest();}/*** 校验订单信息:先扣款,后查询订单详情* @param orderid 前端提供的palpay的订单id* @return 订单存在并已扣款成功返回true*/public boolean verifyorderinfo(string orderid) {boolean f = fal;try {// 1.用户授权支付成功,进行扣款操作this.captureorder(orderid);} catch (exception e) {e.printstacktrace();} finally {// 2.扣款操作失败时也要查询订单,确认是否已扣款try {ordersgetrequest request = new ordersgetrequest(orderid);httprespon<order> respon = client(mode, clientid, clientcret).execute(request);system.out.println("status code: " + respon.statuscode());system.out.println("status: " + respon.result().status());system.out.println("order id: " + respon.result().id());if(respon.result().purchaunits().get(0).payments() != null) {list<capture> captures = respon.result().purchaunits().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());httprespon<order> respon = null;try {respon = client(mode, clientid, clientcret).execute(request);} catch (ioexception e1) {try {log.error("第1次调用paypal扣款失败");respon = client(mode, clientid, clientcret).execute(request);} catch (exception e) {try {log.error("第2次调用payp小儿夜间咳嗽al扣款失败");respon = client(mode, clientid, clientcret).execute(request);} catch (exception e2) {log.error("第3次调用paypal扣款失败,失败原因 {}", e2.getmessage() );}}}if (objectutils.isnotempty(respon)) {log.info("status code = {}, status = {}, orderid = {}", respon.statuscode(), respon.result().status(), respon.result().id());for (linkdescription link : respon.result().links()) {log.info("links-{}: {} \tcall type: {}", link.rel(), link.href(), link.method());}for (purchaunit purchaunit : respon.result().purchaunits()) {for (capture capture : purchaunit.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 = respon.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);httprespon<order> respon = null;try {respon = client(mode, clientid, clientcret).execute(request);} catch (exception e) {try {system.out.println("调用paypal订单查询失败,链接异常1");respon = client(mode, clientid, clientcret).execute(request);} catch (exception e2) {try {system.out.println("调用paypal订单查询失败,链接异常2");respon = client(mode, clientid, clientcret).execute(request);} catch (exception e3) {system.out.println("调用paypal订单查询失败,链接异常3");system.out.println(e3.getmessage());}}}system.out.println("status code: " + respon.statuscode());system.out.println("status: " + respon.result().status());system.out.println("order id: " + respon.result().id());if(respon.result().purchaunits().get(0).payments() != null) {list<capture> captures = respon.result().purchaunits().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 = respon.result().purchaunits().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 : respon.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);httprespon<com.paypal.payments.capture> respon = client(mode, clientid, clientcret).execute(request);system.out.println("status code: " + respon.statuscode());system.out.println("status: " + respon.result().status());system.out.println("capture ids: " + respon.result().id());system.out.println("links: ");for (com.paypal.payments.linkdescription link : respon.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=reprentation");request.requestbody(orderrequest);// paypalclient paypalclient = new paypalclient();httprespon<order> respon = null;try {respon = client(mode, clientid, clientcret).execute(request);} catch (ioexception e1) {try {log.error("第1次调用paypal订单创建失败");respon = client(mode, clientid, clientcret).execute(request);} catch (exception e) {try {log.error("第2次调用paypal订单创建失败");respon = client(mode, clientid, clientcret).execute(request);} catch (exception e2) {log.error("第3次调用paypal订单创建失败,失败原因:{}", e2.getmessage());}}}// string approve = "";map<string,object> map = new hashmap();if (respon.statuscode() == 201) {log.info("status code = {}, status = {}, orderid = {}, intent = {}", respon.statuscode(), respon.result().status(), respon.result().id(), respon.result().checkoutpaymentintent());map.put("id",respon.result().id());for (linkdescription link : respon.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 = respon.result().purchaunits().get(0).amountwithbreakdown().currencycode() + ":" + respon.result().purchaunits().get(0).amountwithbreakdown().value();log.info("total amount: {}", totalamount);// string json= new jsonobject(new json().rialize(respon.result())).tostring(4);// log.info("createorder respon 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支付内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!
本文发布于:2023-04-04 04:19:32,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/aec6ab64eca5dc03bc7e3ef74a5a1f61.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:java后端PayPal支付实现教程.doc
本文 PDF 下载地址:java后端PayPal支付实现教程.pdf
留言与评论(共有 0 条评论) |