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

Laravel中基于Webpay Plus创建自定义支付网关及对接Shopify网关咨询

一、在Laravel框架中创建基于Webpay Plus的自定义支付网关

1. 安装官方SDK

通过Composer安装Transbank的Webpay Plus SDK:

composer require transbank/transbank-sdk

2. 创建自定义支付网关服务类

在app/Services/PaymentGateways目录下创建WebpayPlusGateway.php,封装支付初始化、回调验证核心逻辑:

<?php

namespace App\Services\PaymentGateways;

use Transbank\Webpay\WebpayPlus;
use Transbank\Webpay\WebpayPlus\Transaction;

class WebpayPlusGateway
{
    protected Transaction $transaction;

    public function __construct()
    {
        // 生产环境配置
        WebpayPlus::configureForProduction(env('WEBPAY_COMMERCE_CODE'), env('WEBPAY_API_KEY'));
        // 测试环境请替换为:WebpayPlus::configureForTesting();
        
        $this->transaction = new Transaction();
    }

    // 初始化支付请求
    public function initiatePayment(string $orderId, float $amount, string $returnUrl): object
    {
        return $this->transaction->create(
            $orderId,
            uniqid(), // 唯一会话ID
            $amount,
            $returnUrl
        );
    }

    // 验证支付回调并获取结果
    public function verifyPayment(string $token): object
    {
        return $this->transaction->commit($token);
    }
}

3. 配置环境变量

在.env文件中添加Webpay凭证信息:

WEBPAY_COMMERCE_CODE=你的商户编号
WEBPAY_API_KEY=你的API密钥
WEBPAY_RETURN_URL=https://your-domain.com/webpay/callback

4. 定义支付路由

在routes/web.php中添加支付相关路由:

use App\Http\Controllers\PaymentController;

// 初始化Webpay支付
Route::post('/webpay/init', [PaymentController::class, 'initiatePayment']);
// 处理Webpay支付回调
Route::get('/webpay/callback', [PaymentController::class, 'handlePaymentCallback']);

5. 编写支付控制器逻辑

创建app/Http/Controllers/PaymentController.php,处理支付请求和回调:

<?php

namespace App\Http\Controllers;

use App\Services\PaymentGateways\WebpayPlusGateway;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    protected WebpayPlusGateway $webpay;

    public function __construct(WebpayPlusGateway $webpay)
    {
        $this->webpay = $webpay;
    }

    // 处理支付初始化请求
    public function initiatePayment(Request $request)
    {
        $request->validate([
            'order_id' => 'required|string',
            'amount' => 'required|numeric|min:0.01'
        ]);

        $paymentData = $this->webpay->initiatePayment(
            $request->order_id,
            $request->amount,
            env('WEBPAY_RETURN_URL')
        );

        // 跳转到Webpay支付页面
        return redirect()->to($paymentData->url . '?token_ws=' . $paymentData->token);
    }

    // 处理Webpay支付回调
    public function handlePaymentCallback(Request $request)
    {
        $token = $request->query('token_ws');
        if (!$token) {
            return view('payment.failure', ['message' => '无效的支付令牌']);
        }

        $paymentResult = $this->webpay->verifyPayment($token);

        if ($paymentResult->status === 'AUTHORIZED') {
            // 支付成功:更新订单状态、记录支付日志等逻辑
            return view('payment.success', ['result' => $paymentResult]);
        }

        // 支付失败:处理失败逻辑
        return view('payment.failure', ['result' => $paymentResult]);
    }
}

二、将Webpay Plus与Shopify对接以获取支付记录

1. 准备Shopify API凭证

在Shopify后台创建自定义应用,获取以下信息:

  • 店铺域名(如your-shop.myshopify.com)
  • API访问令牌(需勾选read_payments、write_payments权限)

2. 创建Shopify支付服务类

在app/Services/Shopify目录下创建ShopifyPaymentService.php,封装API调用逻辑:

<?php

namespace App\Services\Shopify;

use GuzzleHttp\Client;

class ShopifyPaymentService
{
    protected Client $client;
    protected string $shopDomain;
    protected string $accessToken;

    public function __construct()
    {
        $this->shopDomain = env('SHOPIFY_SHOP_DOMAIN');
        $this->accessToken = env('SHOPIFY_ACCESS_TOKEN');
        
        $this->client = new Client([
            'base_uri' => "https://{$this->shopDomain}/admin/api/2024-07/",
            'headers' => [
                'X-Shopify-Access-Token' => $this->accessToken,
                'Content-Type' => 'application/json',
            ],
        ]);
    }

    // 获取所有Webpay Plus成功支付记录
    public function getWebpaySuccessPayments(): array
    {
        $response = $this->client->get('payments.json', [
            'query' => [
                'payment_method' => 'webpay_plus', // 需匹配你在Shopify配置的支付方法标识
                'status' => 'success',
                'limit' => 50 // 分页获取,最大100
            ]
        ]);

        return json_decode($response->getBody(), true);
    }

    // 根据订单ID获取对应支付记录
    public function getPaymentsByOrderId(string $orderId): array
    {
        $response = $this->client->get("orders/{$orderId}/payments.json");
        return json_decode($response->getBody(), true);
    }

    // 同步Webpay支付结果到Shopify订单(可选)
    public function syncPaymentToOrder(string $orderId, float $amount): void
    {
        $payload = [
            'payment' => [
                'amount' => $amount,
                'payment_method' => 'webpay_plus',
                'status' => 'success',
                'transaction_id' => uniqid('webpay_')
            ]
        ];

        $this->client->post("orders/{$orderId}/payments.json", [
            'json' => $payload
        ]);
    }
}

3. 配置Shopify环境变量

在.env中添加Shopify相关配置:

SHOPIFY_SHOP_DOMAIN=your-shop.myshopify.com
SHOPIFY_ACCESS_TOKEN=your-shopify-access-token

4. 实现支付记录同步(可选)

如果你的Webpay支付在Laravel系统处理,可在支付回调成功后同步结果到Shopify:

// 在PaymentController的handlePaymentCallback方法中添加
$shopifyService = app(ShopifyPaymentService::class);
// 假设$request->order_id对应Shopify订单ID
$shopifyService->syncPaymentToOrder($request->order_id, $paymentResult->amount);

5. 定时同步支付记录(可选)

若需定期拉取Shopify中的Webpay支付记录,可在app/Console/Kernel.php中添加定时任务:

protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        $shopifyService = app(ShopifyPaymentService::class);
        $payments = $shopifyService->getWebpaySuccessPayments();
        
        // 将支付记录同步到本地数据库或进行其他处理
    })->hourly();
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 13:22:11