Home  >  Article  >  PHP Framework  >  Laravel Development: How to handle subscription payments using Laravel Cashier and Authorize.net?

Laravel Development: How to handle subscription payments using Laravel Cashier and Authorize.net?

王林
王林Original
2023-06-13 19:15:411266browse

With the continuous development of e-commerce, subscription payment models are becoming more and more popular. Laravel Cashier is a payment tool based on the Laravel framework that makes managing subscriptions and collecting payments very simple. This article will explain how to use Laravel Cashier along with Authorize.net in a Laravel application to process subscription payments.

  1. Installing Laravel Cashier

Before you begin, you need to make sure you have installed the Laravel framework and Composer package manager. Enter the following command in the terminal to install Laravel Cashier:

composer require laravel/cashier

Once it is installed successfully, you need to generate the migration table for Cashier. You can run the following command in the terminal:

php artisan migrate

This will generate the required database migration files for the payment-related Cashier table.

  1. Configure Authorize.net API

Before using Authorize.net to process payments, you need to install the service and obtain API credentials (API Login ID and Transaction Key).

You can perform these operations through the following steps:

  • Go to https://www.authorize.net/ to register an account
  • After logging in, click on the menu on the left Select "Account" in "Security Settings", then select "Settings"
  • In "Security Settings", select "API Credentials & Keys"
  • Click "New Transaction Key", enter the required information, and then Click "Submit"
  • The API Login ID and Transaction Key will be displayed in the pop-up window. Please make a copy and keep it in a safe place.
  1. Configuring Laravel Cashier

Before you begin, you need to configure the parameters in the cashier.php file. This file can be created in the config folder with the following command:

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

Next, you need to set the Authorize.net API related parameters in the .env file:

CASHIER_ENV=production
CASHIER_CURRENCY=usd
AUTHORIZE_API_LOGIN_ID=YOUR_API_LOGIN_ID
AUTHORIZE_TRANSACTION_KEY=YOUR_TRANSACTION_KEY
  1. Create a subscription plan

Before using Laravel Cashier and Authorize.net to process subscription payments, you need to create a subscription plan. You can create a subscription plan through the following command:

php artisan make:model Plan -m

This command will create a Plan model in the app folder and generate a migration table for it. The migration file can now be opened for editing and the necessary fields added. The following is an example for reference:

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();
});

After executing the migration file, the table needs to be created in the database. Run the following command in the terminal:

php artisan migrate

Next, you need to define the necessary properties and methods in the Plan model. Here is an example:

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 method will create the Authorize.net subscription plan and return the relevant information.

  1. Processing Subscription Payments

Once the subscription plan has been created, it is now time to send the subscription link to the subscriber. Next, subscribers can use Link to click on the link to pay for their subscription.

When creating a subscription, you need to set the subscription plan and user-related information.

The following is a sample controller method:

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');
}

In this example, we use the newSubscription method to create a new subscription for the user. Note that $request->stripeToken is a token generated using Stripe Checkout. getUserPlanThe method is defined in the Plan model and is used to obtain the current user's subscription plan.

After creating the subscription, we save the ID of the created Authorize.net subscription plan into the Subscription model.

  1. Handling Unsubscription

When a user wants to cancel a subscription, they need to do the following:

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.');
}

In this example, we use cancelMethod to cancel a user's Laravel Cashier subscription plan and cancel the subscription plan using the methods provided in Authorize.net.

Summary

Processing subscription payments is easy with Laravel Cashier and Authorize.net. Just follow the steps above to quickly set up and implement. Laravel Cashier provides convenient payment tools, why not implement such a new model to meet the changing market needs?

The above is the detailed content of Laravel Development: How to handle subscription payments using Laravel Cashier and Authorize.net?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn