PayPal支付對接php

丶XianGang發表於2024-08-07
# 安裝composer 包
 "paypal/rest-api-sdk-php": "^1.14",
 "paypal/paypal-checkout-sdk": "^1.0"


use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Rest\ApiContext;



    public function paypal()
    {
        $price = '1';
        # 訂單編號
        $orderSn = makePaySn(1);
        $client_id = \think\Env::get('paypal.client_id');
        $secret_key = \think\Env::get('paypal.secret');
        $paypal = new ApiContext(new OAuthTokenCredential($client_id, $secret_key));
        # 設定環境
        $paypal->setConfig(['mode' => 'sandbox']); //設定線上環境,預設是sandbox(沙箱模式)live(正式環境)
        $payer = new Payer();
        # 付款方式
        $payer->setPaymentMethod('paypal');
        $item = new Item();
        //USD=美金
        $item->setName('充值金豆')->setCurrency('USD')->setQuantity(1)->setPrice($price);
        # 支付清單
        $itemList = new ItemList();
        $itemList->setItems([$item]);
        $details = new Details();
        $details->setShipping(0)->setSubtotal($price);
        # setCurrency 貨幣 setTotal 向此人付付款金額  setDetails 付款金額其他資訊
        $amount = new Amount();
        $amount->setCurrency('USD')->setTotal($price)->setDetails($details);
        # 支付
        $transaction = new Transaction();
        $transaction->setAmount($amount)->setItemList($itemList)->setDescription('下單支付')
            ->setInvoiceNumber($orderSn);
        # 設定回撥
        $redirectUrls = new RedirectUrls();
        $redirectUrls
            # 支付成功回撥地址
            ->setReturnUrl(request()->domain() . '/api/recharge_order/pay_success_callback?success=true')
            # 取消訂單回撥地址
            ->setCancelUrl(request()->domain() . '/api/recharge_order/pay_success_callback?success=false');

        $payment = new Payment();
        # ["sale", "authorize", "order"]  setPayer=來源方式
        $payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transaction]);
        try {
            $payment->create($paypal);
        } catch (PayPalConnectionException $e) {
            $this->error($e->getData());
        }
        $approvalUrl = $payment->getApprovalLink();
        $this->success("建立成功", [
            'pay' => $approvalUrl
        ]);
    }
    /**
     * Notes:paypal支付回撥
     * User: Ixiangang
     * Date: 2024/7/12
     * Time:19:49
     */
    public function pay_success_callback()
    {
        $success = $this->request->get('success');
        if ($success == 'true') {
            $paymentID = $this->request->get('paymentId');
            $payerId = $this->request->get('PayerID');
            $clientId = \think\Env::get('paypal.client_id');
            $secret = \think\Env::get('paypal.secret');
            $oAuth = new \PayPal\Auth\OAuthTokenCredential($clientId, $secret);
            $apiContext = new \PayPal\Rest\ApiContext($oAuth);
            if (!$this->debug) {
                $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.
                $out_trade_no = $payment->getTransactions()[0]->getInvoiceNumber();//string(20) "23121117295077560001" 平臺內訂單編號
                $payNum = $payment->getTransactions()[0]->getRelatedResources()[0]->getSale()->getId();//這是三方支付的流水單號,必須儲存,在退款時會使用到 string(17) "9X01559580718392X"
                $transactionState = $payment->getTransactions()[0]->getRelatedResources()[0]->getSale()->getState();//Possible values: completed, partially_refunded, pending, refunded, denied.
                if ($paymentState == 'approved' && $transactionState == 'completed') {
                    # 這裡寫業務邏輯
                } else {
                    //paypal回撥錯誤,paypal狀態不正確
                    echo "error";//返回錯誤標識
                    /*$fail_url = request()->domain()."/index.html#/pagesA/payment_status/payment_status?status=0";
                    //處理成功的邏輯,例如:判斷支付金額與訂單金額,更新訂單狀態等
                    header("Location: {$fail_url}");*/
                }
            } catch (\Exception $e) {
                echo "error";//返回錯誤標識
                /*$fail_url = request()->domain()."/index.html#/pagesA/payment_status/payment_status?status=0";
                //處理成功的邏輯,例如:判斷支付金額與訂單金額,更新訂單狀態等
                header("Location: {$fail_url}");*/
            }
        } else {
            echo "error";//返回錯誤標識
            /*$fail_url = request()->domain()."/index.html#/pagesA/payment_status/payment_status?status=0";
            //處理成功的邏輯,例如:判斷支付金額與訂單金額,更新訂單狀態等
            header("Location: {$fail_url}");*/
        }
    }

相關文章