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

隨著電子商務的不斷發展,訂閱付款模式越來越受歡迎。 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
任務管理工具:遠程項目的優先級和跟踪進度任務管理工具:遠程項目的優先級和跟踪進度May 02, 2025 am 12:25 AM

taskManagementsToolSareEssentialForefectiverMototeprojectManagementbyPrioritizingTaskSandTrackingProgress.1)USETOOLSLIKETRELLOANDASANATASANATOSETPRIORITIONTAGS.2)

最新的Laravel版本如何提高性能?最新的Laravel版本如何提高性能?May 02, 2025 am 12:24 AM

Laravel10enhancesPerformancEthroughSeveralKeyKeyFeatures.1)itintroducesquereBuilderCachingTordorcachingTordOuctedSataBaseload.2)itoptimiesseloizeseloquentmodelloAdingwithlazyproxies.3)

全棧Laravel應用程序的部署策略全棧Laravel應用程序的部署策略May 02, 2025 am 12:22 AM

最佳的全棧Laravel應用部署策略包括:1.零停機部署,2.藍綠部署,3.持續部署,4.金絲雀發布。 1.零停機部署使用Envoy或Deployer自動化部署過程,確保應用在更新時保持可用。 2.藍綠部署通過維護兩個環境實現無停機部署,並允許快速回滾。 3.持續部署通過GitHubActions或GitLabCI/CD自動化整個部署流程。 4.金絲雀發布通過Nginx配置,將新版本逐步推廣給用戶,確保性能優化和快速回滾。

擴展全堆棧Laravel應用程序:最佳實踐和技術擴展全堆棧Laravel應用程序:最佳實踐和技術May 02, 2025 am 12:22 AM

toscalealaravelApplication有效,焦點databaseSharding,緩存,負載平衡和microservices.1)實現DataBasEshardingTodistaCripedataCrossmultipledataBasesForimProvesforimPrevperformance.2)uselaravel'scachingsystemystemystemystemywithredsormememememememcachedtebachedtebab

沉默的鬥爭:克服分佈式團隊中的溝通障礙沉默的鬥爭:克服分佈式團隊中的溝通障礙May 02, 2025 am 12:20 AM

doovercomecommunicationbarriersIndistributedTeams,使用:1)VideoCallSforface-to-Faceinteraction,2)setClearresponsEtimepections,3)chooseappropropropraproproprapropropriatecommunicationTools,4)CreatseateAteAteAteamCommunicationGuide和5)建立PemersonalBoundariestAriestOpeopReventBreventBurniationBurnication.the

使用Laravel Blade在全棧項目中進行前端模板使用Laravel Blade在全棧項目中進行前端模板May 01, 2025 am 12:24 AM

laravelbladeenhancesfrontendtemplatinginflatinginflationll-stackprojectsbyferingCleanSyntaxandaxandpoperfelfulfeatures.1)itallowsforeasyvariableasyvariabledisplayandControlstructures.2)bladesuportsuportsuportscreatingingingingingingingingingingangingandredreingscomponents components components components,aidinginmanagingcomplexuis.3)

使用Laravel:實用教程構建全堆棧應用程序使用Laravel:實用教程構建全堆棧應用程序May 01, 2025 am 12:23 AM

laravelisidealforll-stackapplicationsduetoitselegantsyntax,complastissionecosystem和perperatedfulfeatures.1)useeloquentormforintuivelbackenddatamanipulation,butavoidn 1queryissues.2)

您使用哪種工具來保持遠程角色保持連接?您使用哪種工具來保持遠程角色保持連接?May 01, 2025 am 12:21 AM

forremotework,iusezoomforvideOcalls,Slackformessing,trelloforprojectmanagement,and giThubForCodeCollaboration.1)Zoomisreliable forlailible forlargemeetingsbuthastimelimitsonthefreeversion.2)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具