環境準備
更多API代碼範本
#註冊paypal開發者帳號
用剛才建立的測試帳號登入沙盒測試站點,查看金額和交易資訊www.sandbox.paypal.com
帳號預設為建立好了一個Default Application,點選檢視取得ClientId和Secret;儲存起來,接下來介面呼叫會使用到;(上線時請重新建立一個Live的應用程式)
下載SDK
composer require paypal/rest-api-sdk-php
以下是產生支付的程式碼片段,偽代碼
function createPayPal(){ $shippingPrice = 2; $taxPrice = 0; $subTotal = 26; $item1 = new PayPal\Api\Item(); $item1->setName("产品2")->setCurrency("USD")->setQuantity(1)->setPrice(10); $item2 = new PayPal\Api\Item(); $item2->setName("产品1")->setCurrency("USD")->setQuantity(2)->setPrice(8); $itemList = new PayPal\Api\ItemList(); $itemList->addItems([$item1,$item2]); // Set payment details $details = new PayPal\Api\Details(); $details->setShipping($shippingPrice)->setTax($taxPrice)->setSubtotal($subTotal); // Set payment amount //注意,此处的subtotal,必须是产品数*产品价格,所有值必须是正确的,否则会报错 $total = $shippingPrice + $subTotal + $taxPrice; $amount = new PayPal\Api\Amount(); $amount->setCurrency("USD")->setTotal($total)->setDetails($details); // Set transaction object $transaction = new PayPal\Api\Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("这是交易描述") ->setInvoiceNumber(uniqid());//setInvoiceNumber为支付唯一标识符,在使用时建议改成订单号 $payer = new PayPal\Api\Payer(); $payer->setPaymentMethod('paypal');//["credit_card", "paypal"] $redirectUrls = new PayPal\Api\RedirectUrls(); $redirectUrl = "http://test.com/redirect/success";//支付成功跳转的回调 $cancelUrl = "http://test.com/redirect/cancel";//取消支付的回调 $redirectUrls->setReturnUrl($redirectUrl)->setCancelUrl($cancelUrl); // Create the full payment object $payment = new PayPal\Api\Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->addTransaction($transaction); try { $clientId = "xxxxxx";//上面应用的clientId和secret $secret = "XXXXXX"; $oAuth = new \PayPal\Auth\OAuthTokenCredential($clientId, $secret); $apiContext = new \PayPal\Rest\ApiContext($oAuth); if(env('APP_DEBUG') === false ){ $apiContext->setConfig(['mode' => 'live']);//设置线上环境,默认是sandbox } $payment->create($apiContext); $approvalUrl = $payment->getApprovalLink(); dd($approvalUrl);//这个是请求支付的链接,在浏览器中请求此链接就会跳转到支付页面 } catch (\Exception $e) { dd($e->getMessage());//错误提示 } }
function payRedirect(Request $request) { $paymentID = $request->get('paymentId'); $payerId = $request->get('PayerID'); $clientId = "xxxxxx";//上面应用的clientId和secret $secret = "XXXXXX"; $oAuth = new \PayPal\Auth\OAuthTokenCredential($clientId, $secret); $apiContext = new \PayPal\Rest\ApiContext($oAuth); if(env('APP_DEBUG') === false ){ $apiContext->setConfig(['mode' => 'live']);//设置线上环境,默认是sandbox } $payment = \PayPal\Api\Payment::get($paymentID, $apiContext); $execute = new \PayPal\Api\PaymentExecution(); $execute->setPayerId($payerId); try{ $payment = $payment->execute($execute, $apiContext);//执行,从paypal获取支付结果 $paymentState = $payment->getState();//Possible values: created, approved, failed. $invoiceNum = $payment->getTransactions()[0]->getInvoiceNumber(); $payNum = $payment->getTransactions()[0]->getRelatedResources()[0]->getSale()->getId();//这是支付的流水单号,必须保存,在退款时会使用到 $total = $payment->getTransactions()[0]->getRelatedResources()[0]->getSale()->getAmount()->getTotal();//支付总金额 $transactionState = $payment->getTransactions()[0]->getRelatedResources()[0]->getSale()->getState();//Possible values: completed, partially_refunded, pending, refunded, denied. if($paymentState == 'approved' && $transactionState == 'completed'){ //处理成功的逻辑,例如:判断支付金额与订单金额,更新订单状态等 return "success";//返回成功标识 }else{ //paypal回调错误,paypal状态不正确 return "error";//返回错误标识 } }catch(\Exception $e){ dd($e->getMessage()); } }
#d:
##退款必須要有支付成功的流水單號
退款成功之後,在帳號的交易記錄中不體現,測試時請登入測試帳號自己記錄餘額的變更情況,以確定退款是否成功
商家帳號會減少餘額並增加手續費(手續費用是之前付款多收的),用戶帳號會增加餘額###更多介面程式碼範例############http://paypal. github.io/PayPal-PHP-SDK/sample/############推薦:《###PHP影片教學###》###function refundOrder() { try{ $refundRequest = new \PayPal\Api\RefundRequest(); $amount = new \PayPal\Api\Amount(); $amount->setCurrency("USD")->setTotal(10);//退总金额 $refundRequest->setAmount($amount); $refundRequest->setDescription("退款测试"); $sale = new \PayPal\Api\Sale(); $sale->setId("XXXXXXXXX");//支付单号,支付成功时保存的支付流水单号 $clientId = "xxxxxx";//上面应用的clientId和secret $secret = "XXXXXX"; $oAuth = new \PayPal\Auth\OAuthTokenCredential($clientId, $secret); $apiContext = new \PayPal\Rest\ApiContext($oAuth); if(env('APP_DEBUG') === false ){ $apiContext->setConfig(['mode' => 'live']);//设置线上环境,默认是sandbox } $detailedRefund = $sale->refundSale($refundRequest, $apiContext);//调接口 $refundState = $detailedRefund->getState();//Possible values: pending, completed, cancelled, failed. //var_dump($refundedSale); if($refundState == 'completed'){ //退款成功,返回 }else{ dd('paypal 退款失败, 状态不正确'); } }catch (\Exception $exception){ dd($exception->getMessage());//发生异常 } }
以上是詳解PHP對接paypal支付的詳細內容。更多資訊請關注PHP中文網其他相關文章!