PayPal支付对接php

# 安装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}");*/
        }
    }

 

posted @ 2024-08-07 08:50  丶XianGang  阅读(4)  评论(0编辑  收藏  举报