首頁  >  文章  >  php框架  >  Laravel開發:如何使用Laravel Cashier和Authorize.net處理訂閱付款?

Laravel開發:如何使用Laravel Cashier和Authorize.net處理訂閱付款?

王林
王林原創
2023-06-13 19:15:411224瀏覽

隨著電子商務的不斷發展,訂閱付款模式越來越受歡迎。 Laravel Cashier是一個基於Laravel框架的付款工具,它使得管理訂閱和收取付款變得非常簡單。本文將介紹如何在Laravel應用程式中使用Laravel Cashier以及Authorize.net來處理訂閱付款。

  1. 安裝Laravel Cashier

在開始之前,需要確保你已經安裝了Laravel框架和Composer套件管理器。在終端機輸入以下指令來安裝Laravel Cashier:

composer require laravel/cashier

一旦它安裝成功,你需要為Cashier產生遷移表。可以在終端機執行以下命令:

php artisan migrate

這將為付款相關的Cashier表產生所需的資料庫遷移檔案。

  1. 設定Authorize.net API

在使用Authorize.net處理付款之前,需要安裝服務並取得API憑證(API Login ID和Transaction Key)。

可以透過以下步驟執行這些操作:

  • 前往https://www.authorize.net/註冊一個帳號
  • 登入後,在左側選單中選擇“Account”,再選擇“Settings”
  • 在“Security Settings”中,選擇“API Credentials & Keys”
  • 點擊“New Transaction Key”,輸入需要的資訊,再點選「Submit」
  • 在彈出視窗中會顯示API Login ID和Transaction Key。請務必複製並妥善保管。
  1. 設定Laravel Cashier

在開始之前,需要先設定cashier.php檔案中的參數。可以透過以下命令在config資料夾中建立該檔案:

php artisan vendor:publish --tag="cashier-config"

接下來,需要在.env檔案中設定A​​uthorize.net API相關參數:

CASHIER_ENV=production
CASHIER_CURRENCY=usd
AUTHORIZE_API_LOGIN_ID=YOUR_API_LOGIN_ID
AUTHORIZE_TRANSACTION_KEY=YOUR_TRANSACTION_KEY
  1. 建立訂閱計劃

在使用Laravel Cashier和Authorize.net處理訂閱付款之前,需要建立訂閱方案。可以透過以下指令來建立訂閱計畫:

php artisan make:model Plan -m

該指令將在app資料夾中建立一個Plan模型,並為其產生遷移表。現在可以開啟遷移檔案進行編輯,並新增必要的欄位。以下是一個可以參考的範例:

Schema::create('plans', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->string('stripe_id');
    $table->string('authorizenet_id');
    $table->integer('price');
    $table->string('interval');
    $table->integer('interval_count');
    $table->integer('trial_period_days')->nullable();
    $table->timestamps();
});

執行完遷移檔案後,需要在資料庫中建立該表。在終端機中執行以下命令:

php artisan migrate

接下來,需要在Plan模型中定義必要的屬性和方法。以下是一個範例:

use LaravelCashierSubscription;

class Plan extends Model
{
    public function subscriptions()
    {
        return $this->hasMany(Subscription::class);
    }

    public function getPrice()
    {
        return $this->price / 100;
    }

    public function getFormattedPrice()
    {
        return number_format($this->getPrice(), 2);
    }

    public function authorizeNetPlan()
    {
        return AuthorizeNet_Subscription::create([
            'name'                   => $this->name,
            'intervalLength'         => $this->interval_count,
            'intervalUnit'           => $this->interval,
            'startDate'              => date('Y-m-d'),
            'totalOccurrences'       => '9999',
            'trialOccurrences'       => '0',
            'amount'                 => $this->price,
            'trialAmount'            => '0.00',
            'creditCardCardNumber'   => '',
            'creditCardExpirationDate' => '',
            'creditCardCardCode' => ''
        ]);
    }
}

authorizeNetPlan方法將建立Authorize.net訂閱計畫並傳回相關的資訊。

  1. 處理訂閱付款

一旦訂閱計畫已經創建,現在就可以向訂閱者發送訂閱連結。接下來,訂閱者可以使用Link點擊連結進行訂閱付款。

在建立訂閱時,需要設定訂閱方案和使用者相關資訊。

以下是一個範例控制器方法:

public function subscribe(Request $request, Plan $plan)
{
    $user = $request->user();
    
    $subscription = $user->newSubscription('default', $plan->stripe_id)->create($request->stripeToken);

    $authorizeSubscription = $plan->authorizeNetPlan();

    $subscription->authorize_net_id = $authorizeSubscription->getSubscriptionId();
    $subscription->save();

    return redirect()->route('home')->with('success', 'Subscription successful');
}

在這個範例中,我們使用newSubscription方法為使用者建立新的訂閱。注意,$request->stripeToken是使用Stripe Checkout產生的令牌。 getUserPlan方法在Plan模型中定義,用於取得目前使用者的訂閱計畫。

在建立訂閱後,我們將建立的Authorize.net訂閱計畫的ID儲存到Subscription模型中。

  1. 處理取消訂閱

當使用者想要取消訂閱時,需要執行以下操作:

public function cancel(Request $request)
{
    $user = $request->user();

    $subscription = $user->subscription('default');

    $authorizeSubscription = AuthorizeNet_Subscription::cancel($subscription->authorize_net_id);
    
    $subscription->cancel();
    
    return redirect()->route('home')->with('success', 'Subscription cancelled.');
}

在該範例中,我們使用cancel方法取消使用者的Laravel Cashier訂閱計劃,並使用Authorize.net中提供的方法取消訂閱計劃。

總結

使用Laravel Cashier和Authorize.net處理訂閱付款非常簡單。僅需按照上述步驟即可快速設定和實現。 Laravel Cashier提供了便利的付款工具,何不實現這樣一種新模式,以滿足日益變化的市場需求呢?

以上是Laravel開發:如何使用Laravel Cashier和Authorize.net處理訂閱付款?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn