PayPal Java SDK 전체 예 – Java 클라이언트를 사용하여 PayPal 권한 부여 REST API를 호출하는 방법은 무엇입니까?
게시 됨: 2019-03-18 PayPal
은 최고의 온라인 Payment
송금 서비스 중 하나입니다. 미친 숫자와 함께 나날이 성장하고 있다는 것은 의심의 여지가 없습니다.
저는 개인적으로 PayPal Java Developer APIs
에 대한 직접적인 경험이 있으며 모든 Crunchify 독자와 경험을 공유하고 싶습니다.
이 튜토리얼에서는 PayPal Java SDK 최신 버전인 1.14.0
을 사용합니다.
다음은 Java Eclipse 프로젝트에 추가할 maven 종속성입니다.
1 2 3 4 5 |
< dependency > < groupId > com . paypal . sdk < / groupId > < artifactId > rest - api - sdk < / artifactId > < version > LATEST < / version > < / dependency > |
위의 PayPal maven 종속성을 Java 프로젝트에 추가하면 랩톱/데스크톱에서 볼 수 있습니다.
이 튜토리얼의 목적
- PayPal API를 사용하여 고객의 계정
put hold
할 수 있습니다. - 동일한 방법으로 구매
capture money
할 수 있습니다. - API를 사용하여 고객에게
refund
할 수 있습니다. - 또한 이전에 계정에 설정
void any hold
. - 위의 모든 작업을 수행할 수 있는 간단한 단계가 있으며 이것이 이 자습서에서 수행할 작업입니다. 주로 우리는 고객의 계정에 HOLD를 둘 것입니다.
내가 무엇이 필요 하나?
PayPal 계정이 필요합니다. 아래 단계를 따르십시오.
-
official PayPal
계정 만들기 - https://developer.paypal.com/developer/applications 링크를 사용하여 PayPal 개발자 포털에 로그인합니다.
- 이 링크를 사용하여 새 앱 만들기: https://developer.paypal.com/developer/applications/create
- 프로그램에서
paypalContext
를 생성하는 데 필요한ClientID
및ClientSecret
을 가져옵니다.
ClientID와 ClientSecret이 있으면 다음은 Java 프로그램 crunchifyCapturePayPalAPI.java 작성을 시작하는 것입니다.
다음은 이 프로그램의 전체 논리입니다.
-
Payer
객체 생성 및 PaymentMethod 설정 -
RedirectUrls
설정 및 cancelURL 및 returnURL 설정 -
Details
설정 및 PaymentDetails 추가 -
Amount
설정 -
Transaction
설정 - 결제 세부정보 추가 및
authorize
의도 설정 -
clientID
,clientSecret
및mode
를 전달하여 APIContext 생성 -
Payment
객체 생성 및 지불 ID 가져오기 -
payerID
를 PaymentExecution 객체로 설정 -
Execute Payment
및 승인 받기
완전한 코드:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
package crunchify . com . paypal . sdk ; import java . util . ArrayList ; import java . util . List ; import com . paypal . api . payments . Amount ; import com . paypal . api . payments . Authorization ; import com . paypal . api . payments . Details ; import com . paypal . api . payments . Links ; import com . paypal . api . payments . Payer ; import com . paypal . api . payments . Payment ; import com . paypal . api . payments . PaymentExecution ; import com . paypal . api . payments . RedirectUrls ; import com . paypal . api . payments . Transaction ; import com . paypal . base . rest . APIContext ; import com . paypal . base . rest . PayPalRESTException ; /** * @author Crunchify.com * Version: 1.1.0 * */ public class CrunchifyPayPalSDKTutorial { private static String crunchifyID = "<!---- Add your clientID Key here ---->" ; private static String crunchifySecret = "<!---- Add your clientSecret Key here ---->" ; private static String executionMode = "sandbox" ; // sandbox or production public static void main ( String args [ ] ) { CrunchifyPayPalSDKTutorial crunchifyObj = new CrunchifyPayPalSDKTutorial ( ) ; // How to capture PayPal Payment using Java SDK? doCapture() PayPal SDK call. crunchifyObj . crunchifyCapturePayPalAPI ( ) ; } // This is simple API call which will capture a specified amount for any given // Payer or User public void crunchifyCapturePayPalAPI ( ) { /* * Flow would look like this: * 1. Create Payer object and set PaymentMethod * 2. Set RedirectUrls and set cancelURL and returnURL * 3. Set Details and Add PaymentDetails * 4. Set Amount * 5. Set Transaction * 6. Add Payment Details and set Intent to "authorize" * 7. Create APIContext by passing the clientID, secret and mode * 8. Create Payment object and get paymentID * 9. Set payerID to PaymentExecution object * 10. Execute Payment and get Authorization * */ Payer crunchifyPayer = new Payer ( ) ; crunchifyPayer . setPaymentMethod ( "paypal" ) ; // Redirect URLs RedirectUrls crunchifyRedirectUrls = new RedirectUrls ( ) ; crunchifyRedirectUrls . setCancelUrl ( "http://localhost:3000/crunchifyCancel" ) ; crunchifyRedirectUrls . setReturnUrl ( "http://localhost:3000/crunchifyReturn" ) ; // Set Payment Details Object Details crunchifyDetails = new Details ( ) ; crunchifyDetails . setShipping ( "2.22" ) ; crunchifyDetails . setSubtotal ( "3.33" ) ; crunchifyDetails . setTax ( "1.11" ) ; // Set Payment amount Amount crunchifyAmount = new Amount ( ) ; crunchifyAmount . setCurrency ( "USD" ) ; crunchifyAmount . setTotal ( "6.66" ) ; crunchifyAmount . setDetails ( crunchifyDetails ) ; // Set Transaction information Transaction crunchifyTransaction = new Transaction ( ) ; crunchifyTransaction . setAmount ( crunchifyAmount ) ; crunchifyTransaction . setDescription ( "Crunchify Tutorial: How to Invoke PayPal REST API using Java Client?" ) ; List < Transaction > crunchifyTransactions = new ArrayList < Transaction > ( ) ; crunchifyTransactions . add ( crunchifyTransaction ) ; // Add Payment details Payment crunchifyPayment = new Payment ( ) ; // Set Payment intent to authorize crunchifyPayment . setIntent ( "authorize" ) ; crunchifyPayment . setPayer ( crunchifyPayer ) ; crunchifyPayment . setTransactions ( crunchifyTransactions ) ; crunchifyPayment . setRedirectUrls ( crunchifyRedirectUrls ) ; // Pass the clientID, secret and mode. The easiest, and most widely used option. APIContext crunchifyapiContext = new APIContext ( crunchifyID , crunchifySecret , executionMode ) ; try { Payment myPayment = crunchifyPayment . create ( crunchifyapiContext ) ; System . out . println ( "createdPayment Obejct Details ==> " + myPayment . toString ( ) ) ; // Identifier of the payment resource created crunchifyPayment . setId ( myPayment . getId ( ) ) ; PaymentExecution crunchifyPaymentExecution = new PaymentExecution ( ) ; // Set your PayerID. The ID of the Payer, passed in the `return_url` by PayPal. crunchifyPaymentExecution . setPayerId ( "<!---- Add your PayerID here ---->" ) ; // This call will fail as user has to access Payment on UI. Programmatically // there is no way you can get Payer's consent. Payment createdAuthPayment = crunchifyPayment . execute ( crunchifyapiContext , crunchifyPaymentExecution ) ; // Transactional details including the amount and item details. Authorization crunchifyAuthorization = createdAuthPayment . getTransactions ( ) . get ( 0 ) . getRelatedResources ( ) . get ( 0 ) . getAuthorization ( ) ; log ( "Here is your Authorization ID" + crunchifyAuthorization . getId ( ) ) ; } catch ( PayPalRESTException e ) { // The "standard" error output stream. This stream is already open and ready to // accept output data. System . err . println ( e . getDetails ( ) ) ; } } private void log ( String string ) { System . out . println ( string ) ; } } |
Eclipse 콘솔 출력:
기본적으로 PayPal SDK는 DEBUG 모드를 활성화하므로 Eclipse 콘솔에 대한 모든 요청과 응답을 기록합니다.
자세한 정보는 DEBUG 모드를 유지하고 getAuthorization 호출의 자세한 결과를 여기에 제공했습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
13 : 22 : 28.013 [ main ] DEBUG com . paypal . base . ConfigManager - sdk_config . properties not present . Skipping . . . 13 : 22 : 28.212 [ main ] DEBUG com . paypal . base . rest . OAuthTokenCredential - request header : { Authorization = Basic QVNuZG9aaEdGOEg1MFFQSWw5TGl0elhwSDVYTW16YlBwZmxJREFJOGVjUWVwdlJyWVQ4UnBfZUpNQmh1dHJVUHdaZU9CVGJUOE1GRksdfgsdfgsdfg3Q1ZLd0NzZTllRnBIZTNNNWpOR1liNHVxZ3BrNDNFVmFXR2hHNXR2Tk1na1IyZkZMUWdTUmRFY3Q3cG8 = , Accept = application / json , User - Agent = PayPalSDK / PayPal - Java - SDK 1.14.0 ( v = 11 ; vendor = Oracle Corporation ; bit = 64 ; os = Mac_OS_X 10.14.1 ) , Content - Type = application / x - www - form - urlencoded } 13 : 22 : 28.212 [ main ] DEBUG com . paypal . base . rest . OAuthTokenCredential - request body : grant_type = client_credentials 13 : 22 : 28.213 [ main ] DEBUG com . paypal . base . HttpConnection - curl command : curl -- verbose -- request POST 'https://api.sandbox.paypal.com/v1/oauth2/token' \ -- header "Authorization:Basic QVNuZG9aaEdGOEg1MFFQSWw5TGl0elhwSDVYTW16YlBwZmxJREFJOGVjUasdfasdflITlhSZ0xVMGhiOHhpa0M3Q1ZLd0NzZTllRnBIZTNNNWpOR1liNHVxZ3BrNDNFVmFXR2hHNXR2Tk1na1IyZkZMUWdTUmRFY3Q3cG8=" \ -- header "Accept:application/json" \ -- header "User-Agent:PayPalSDK/PayPal-Java-SDK 1.14.0 (v=11; vendor=Oracle Corporation; bit=64; os=Mac_OS_X 10.14.1)" \ -- header "Content-Type:application/x-www-form-urlencoded" \ -- data 'grant_type=client_credentials' 13 : 22 : 28.810 [ main ] DEBUG com . paypal . base . rest . OAuthTokenCredential - response header : { paypal - debug - id = [ 961e2e4122ac1 ] , null = [ HTTP / 1.1 200 OK ] , Paypal - Debug - Id = [ 961e2e4122ac1 ] , Server = [ Apache ] , Connection = [ close ] , Vary = [ Authorization ] , Set - Cookie = [ X - PP - SILOVER = ; Expires = Thu , 01 Jan 1970 00 : 00 : 01 GMT , X - PP - SILOVER = name % 3DSANDBOX3.API.1 % 26silo_version % 3D1880 % 26app % 3Dapiplatformproxyserv % 26TIME % 3D4098358363 % 26HTTP_X_PP_AZ_LOCATOR % 3Dsandbox.slc ; Expires = Mon , 26 Nov 2018 19 : 52 : 28 GMT ; domain = . paypal . com ; path =/ ; Secure ; HttpOnly ] , HTTP_X_PP_AZ_LOCATOR = [ sandbox . slc ] , Content - Length = [ 876 ] , X - PAYPAL - TOKEN - SERVICE = [ IAAS ] , Date = [ Mon , 26 Nov 2018 19 : 22 : 28 GMT ] , Content - Type = [ application / json ] } 13 : 22 : 28.810 [ main ] DEBUG com . paypal . base . rest . OAuthTokenCredential - response : { "scope" : "https://api.paypal.com/v1/payments/.* https://uri.paypal.com/services/payments/refund https://uri.paypal.com/services/applications/webhooks https://uri.paypal.com/services/payments/payment/authcapture https://uri.paypal.com/payments/payouts https://api.paypal.com/v1/vault/credit-card/.* https://uri.paypal.com/services/disputes/read-seller https://uri.paypal.com/services/subscriptions https://uri.paypal.com/services/disputes/read-buyer https://api.paypal.com/v1/vault/credit-card openid https://uri.paypal.com/services/disputes/update-seller https://uri.paypal.com/services/payments/realtimepayment" , "nonce" : "2018-11-26T19:03:03ZymZQ8MNE2MarndZEjUoxwB70puoxUA-NXqc7pUVtVxk" , "access_token" : "A21AAGyWgsdafxUM_1FCE5d9adsfuwfiOB7_4XkX3wKHWXe3nkKgt2bhadflirJsMWP9JAm-pBT2DtUJ5W0A" , "token_type" : "Bearer" , "app_id" : "APP-80W284ads543T" , "expires_in" : 31235 } 13 : 22 : 28.817 [ main ] DEBUG com . paypal . base . rest . PayPalResource - request header : { Authorization = Bearer A21AAGyWgsdafxUM_1FCE5d9adsfuwfiOB7_4XkX3wKHWXe3nkKgt2bhadflirJsMWP9JAm - pBT2DtUJ5W0A , User - Agent = PayPalSDK / ( v = 11 ; vendor = Oracle Corporation ; bit = 64 ; os = Mac_OS_X 10.14.1 ) , PayPal - Request - Id = 74886e72 - 34e4 - 4a0 - 8cd7 - 6adsf63b5dc9 , Accept = application / json , Content - Type = application / json } 13 : 22 : 28.817 [ main ] DEBUG com . paypal . base . rest . PayPalResource - request body : { "intent" : "sale" , "payer" : { "payment_method" : "paypal" } , "transactions" : [ { "amount" : { "currency" : "USD" , "total" : "6.66" , "details" : { "subtotal" : "3.33" , "shipping" : "2.22" , "tax" : "1.11" } } , "description" : "Crunchify Tutorial: How to Invoke PayPal REST API using Java Client?" } ] , "redirect_urls" : { "return_url" : "http://localhost:3000/crunchifyReturn" , "cancel_url" : "http://localhost:3000/crunchifyCancel" } } 13 : 22 : 28.818 [ main ] DEBUG com . paypal . base . HttpConnection - curl command : curl -- verbose -- request POST 'https://api.sandbox.paypal.com/v1/payments/payment' \ -- header "Authorization:Bearer A21AAGyWgsdafxUM_1FCE5d9adsfuwfiOB7_4XkX3wKHWXe3nkKgt2bhadflirJsMWP9JAm-pBT2DtUJ5W0A" \ -- header "User-Agent:PayPalSDK/ (v=11; vendor=Oracle Corporation; bit=64; os=Mac_OS_X 10.14.1)" \ -- header "PayPal-Request-Id:74886e72-34e4-4a70-8cd7-605cd63b5dc9" \ -- header "Accept:application/json" \ -- header "Content-Type:application/json" \ -- data '{ "intent": "sale", "payer": { "payment_method": "paypal" }, "transactions": [ { "amount": { "currency": "USD", "total": "6.66", "details": { "subtotal": "3.33", "shipping": "2.22", "tax": "1.11" } }, "description": "Crunchify Tutorial: How to Invoke PayPal REST API using Java Client?" } ], "redirect_urls": { "return_url": "http://localhost:3000/crunchifyReturn", "cancel_url": "http://localhost:3000/crunchifyCancel" } }' 13 : 22 : 33.407 [ main ] DEBUG com . paypal . base . rest . PayPalResource - response : { "id" : "PAY-25A74012S3552184CLP6EP6A" , "intent" : "sale" , "state" : "created" , "payer" : { "payment_method" : "paypal" } , "transactions" : [ { "amount" : { "total" : "6.66" , "currency" : "USD" , "details" : { "subtotal" : "3.33" , "tax" : "1.11" , "shipping" : "2.22" } } , "description" : "Crunchify Tutorial: How to Invoke PayPal REST API using Java Client?" , "related_resources" : [ ] } ] , "create_time" : "2018-11-26T19:22:32Z" , "links" : [ { "href" : "https://api.sandbox.paypal.com/v1/payments/payment/PAY-25A74012S3552184CLP6EP6A" , "rel" : "self" , "method" : "GET" } , { "href" : "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-9C691969F1033220V" , "rel" : "approval_url" , "method" : "REDIRECT" } , { "href" : "https://api.sandbox.paypal.com/v1/payments/payment/PAY-25A74012S3552184CLP6EP6A/execute" , "rel" : "execute" , "method" : "POST" } ] } createdPayment Obejct Details == > { "id" : "PAY-25A74012S3552184CLP6EP6A" , "intent" : "sale" , "payer" : { "payment_method" : "paypal" } , "transactions" : [ { "related_resources" : [ ] , "amount" : { "currency" : "USD" , "total" : "6.66" , "details" : { "subtotal" : "3.33" , "shipping" : "2.22" , "tax" : "1.11" } } , "description" : "How to Invoke PayPal REST API using Java Client?" } ] , "state" : "created" , "create_time" : "2018-11-26T19:22:32Z" , "links" : [ { "href" : "https://api.sandbox.paypal.com/v1/payments/payment/PAY-25A74012S3552184CLP6EP6A" , "rel" : "self" , "method" : "GET" } , { "href" : "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd\u003d_express-checkout\u0026token\u003dEC-9C691969F1033220V" , "rel" : "approval_url" , "method" : "REDIRECT" } , { "href" : "https://api.sandbox.paypal.com/v1/payments/payment/PAY-25A74012S3552184CLP6EP6A/execute" , "rel" : "execute" , "method" : "POST" } ] } 13 : 22 : 33.414 [ main ] DEBUG com . paypal . base . rest . PayPalResource - request header : { Authorization = Bearer A21AAGyWgkMoxUM_1FCE5d948J5SAxIuwfiOB7_4XkX3wKHWXe3nkKgt2bhtXISnazHlE9yzlirJsMWP9JAm - pBT2DtUJ5W0A , User - Agent = PayPalSDK / ( v = 11 ; vendor = Oracle Corporation ; bit = 64 ; os = Mac_OS_X 10.14.1 ) , PayPal - Request - Id = e47412c8 - 2c1f - 4505 - b1a3 - 7b4723eb99f4 , Accept = application / json , Content - Type = application / json } 13 : 22 : 33.415 [ main ] DEBUG com . paypal . base . rest . PayPalResource - request body : { "payer_id" : "1Z232AMNN" } 13 : 22 : 33.415 [ main ] DEBUG com . paypal . base . HttpConnection - curl command : curl -- verbose -- request POST 'https://api.sandbox.paypal.com/v1/payments/payment/PAY-25A74012S3552184CLP6EP6A/execute' \ -- header "Authorization:Bearer A21AAGyWgsdafxUM_1FCE5d9adsfuwfiOB7_4XkX3wKHWXe3nkKgt2bhadflirJsMWP9JAm-pBT2DtUJ5W0A" \ -- header "User-Agent:PayPalSDK/ (v=11; vendor=Oracle Corporation; bit=64; os=Mac_OS_X 10.14.1)" \ -- header "PayPal-Request-Id:eadf412c8-2c1f-4505-b1a3-7basdaf99f4" \ -- header "Accept:application/json" \ -- header "Content-Type:application/json" \ -- data '{ "payer_id": "1Z232AMNN" }' 13 : 22 : 34.016 [ main ] ERROR com . paypal . base . HttpConnection - Response code : 400 Error response : { "name" : "PAYMENT_NOT_APPROVED_FOR_EXECUTION" , "message" : "Payer has not approved payment" , "information_link" : "https://developer.paypal.com/docs/api/payments/#errors" , "debug_id" : "113d5208bf8d3" } name : PAYMENT_NOT_APPROVED_FOR_EXECUTION message : Payer has not approved payment details : null debug - id : 113d5208bf8d3 information - link : https : //developer.paypal.com/docs/api/payments/#errors |
같은 방식으로 다음 튜토리얼에서 돈을 회수하고, refund money
하고, 지불인의 계정에 void any authorization
how to capture money
에 대한 자세한 내용을 제공합니다.
