You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Codeigniter 4.3.5中集成PayPal?求最优实现方案

在Codeigniter 4.3.5中集成PayPal支付的最优方案

你遇到的paypal/rest-api-sdk-php已被官方废弃,当前PayPal官方推荐使用PayPal Checkout SDK(paypal/paypal-checkout-sdk)作为PHP集成的标准方案,以下是完整的CI4集成步骤:

1. 安装官方推荐的PayPal SDK

执行Composer命令安装最新的PayPal Checkout SDK:

composer require paypal/paypal-checkout-sdk

2. 配置PayPal凭据

在CI4的.env文件中添加沙箱/生产环境的凭据(前往PayPal开发者平台获取):

# PayPal 沙箱环境(测试用)
PAYPAL_MODE=sandbox
PAYPAL_CLIENT_ID=你的沙箱客户端ID
PAYPAL_CLIENT_SECRET=你的沙箱密钥

# 生产环境(上线切换)
# PAYPAL_MODE=live
# PAYPAL_CLIENT_ID=你的生产客户端ID
# PAYPAL_CLIENT_SECRET=你的生产密钥

创建app/Config/PayPal.php配置类,统一读取环境变量:

<?php namespace Config;

use CodeIgniter\Config\BaseConfig;

class PayPal extends BaseConfig
{
    public $mode;
    public $clientId;
    public $clientSecret;

    public function __construct()
    {
        $this->mode = env('PAYPAL_MODE', 'sandbox');
        $this->clientId = env('PAYPAL_CLIENT_ID');
        $this->clientSecret = env('PAYPAL_CLIENT_SECRET');
    }
}

3. 封装PayPal服务类

创建app/Services/PayPalService.php,封装SDK核心操作:

<?php namespace App\Services;

use Config\PayPal;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;

class PayPalService
{
    protected $client;

    public function __construct()
    {
        $config = new PayPal();
        $environment = $config->mode === 'sandbox' 
            ? new SandboxEnvironment($config->clientId, $config->clientSecret)
            : new ProductionEnvironment($config->clientId, $config->clientSecret);
        
        $this->client = new PayPalHttpClient($environment);
    }

    // 创建支付订单
    public function createOrder(float $amount, string $currency = 'USD', string $description = '订单支付')
    {
        $request = new OrdersCreateRequest();
        $request->prefer('return=representation');
        $request->body = [
            "intent" => "CAPTURE",
            "purchase_units" => [[
                "amount" => [
                    "currency_code" => $currency,
                    "value" => number_format($amount, 2, '.', '')
                ],
                "description" => $description
            ]],
            "application_context" => [
                "return_url" => base_url('paypal/success'),
                "cancel_url" => base_url('paypal/cancel')
            ]
        ];

        try {
            $response = $this->client->execute($request);
            return $response->result;
        } catch (\Exception $e) {
            log_message('error', 'PayPal 创建订单失败: ' . $e->getMessage());
            return false;
        }
    }

    // 捕获支付金额(完成支付)
    public function captureOrder(string $orderId)
    {
        $request = new OrdersCaptureRequest($orderId);
        $request->prefer('return=representation');

        try {
            $response = $this->client->execute($request);
            return $response->result;
        } catch (\Exception $e) {
            log_message('error', 'PayPal 捕获订单失败: ' . $e->getMessage());
            return false;
        }
    }
}

4. 创建支付控制器

创建app/Controllers/PayPal.php,处理支付流程各节点:

<?php namespace App\Controllers;

use App\Services\PayPalService;

class PayPal extends BaseController
{
    protected $payPalService;

    public function __construct()
    {
        $this->payPalService = new PayPalService();
    }

    // 发起支付(跳转PayPal页面)
    public function createPayment()
    {
        // 替换为实际业务的订单金额
        $orderAmount = 10.00;
        $order = $this->payPalService->createOrder($orderAmount);

        if (!$order) {
            return view('error', ['message' => '支付订单创建失败']);
        }

        // 跳转到PayPal支付授权页面
        foreach ($order->links as $link) {
            if ($link->rel === 'approve') {
                return redirect()->to($link->href);
            }
        }

        return view('error', ['message' => '未找到支付跳转链接']);
    }

    // 支付成功回调
    public function success()
    {
        $orderId = $this->request->getGet('token');
        if (!$orderId) {
            return view('error', ['message' => '无效的订单ID']);
        }

        $captureResult = $this->payPalService->captureOrder($orderId);
        if (!$captureResult || $captureResult->status !== 'COMPLETED') {
            return view('error', ['message' => '支付验证失败']);
        }

        // 这里添加业务逻辑:更新订单状态、记录支付日志、扣减库存等
        log_message('info', 'PayPal支付成功,订单ID: ' . $orderId);

        return view('paypal/success', ['order' => $captureResult]);
    }

    // 支付取消回调
    public function cancel()
    {
        return view('paypal/cancel', ['message' => '您已取消支付']);
    }
}

5. 可选:前端集成智能支付按钮

如果不需要跳转PayPal页面,可使用PayPal智能按钮实现内嵌支付:

<div id="paypal-button-container"></div>

<script src="https://www.paypal.com/sdk/js?client-id=<?= env('PAYPAL_CLIENT_ID') ?>&currency=USD"></script>
<script>
paypal.Buttons({
    createOrder: function(data, actions) {
        // 调用后端接口创建订单
        return fetch('/paypal/createOrderAjax', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({amount: 10.00})
        }).then(res => res.json()).then(orderData => orderData.id);
    },
    onApprove: function(data, actions) {
        // 完成支付并跳转成功页
        return actions.order.capture().then(details => {
            window.location.href = '/paypal/success?token=' + data.orderID;
        });
    }
}).render('#paypal-button-container');
</script>

同时在PayPal控制器中添加AJAX创建订单的方法:

public function createOrderAjax()
{
    if (!$this->request->isAJAX()) return $this->failForbidden();
    
    $amount = $this->request->getJSON()->amount ?? 0;
    if ($amount <= 0) return $this->fail('无效的支付金额', 400);

    $order = $this->payPalService->createOrder($amount);
    return $order ? $this->respond(['id' => $order->id]) : $this->fail('订单创建失败', 500);
}

内容的提问来源于stack exchange,提问作者Mani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 14:55:03