您好,登錄后才能下訂單哦!
PHP對接 paypal 支付的方法?這個問題可能是我們日常學習或工作經常見到的。希望通過這個問題能讓你收獲頗深。下面是小編給大家帶來的參考內容,讓我們一起來看看吧!
環境準備
注冊paypal賬號
注冊paypal開發者賬號
創建沙盒應用APP
下載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()); } }
退款
退款必須要有支付成功的流水單號
一個流水單號可以進行多次退款
退款成功之后,在賬號的交易記錄中不體現,測試時請登錄測試賬號自己記錄一下余額的變化情況,以確定退款是否成功
商家賬號會減少余額并增加手續費(手續費是之前付款多收的),用戶賬號會增加余額
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 支付的方法大概了解了嗎?希望文章內容對大家有所幫助。如果想了解更多相關文章內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。