Create a subscription form using Laravel and the Paystack API

Use paystack api to create Laravel subscription form

To create a subscription form using Laravel and the Paystack API, you will need to use the Paystack PHP library and the subscription.create API endpoint. This endpoint allows you to create a subscription plan and a customer, and then associate the customer with the plan.

Here is an example of how you could use the subscription.create API endpoint to create a subscription form in Laravel:

Copy code<?php

namespace App\Http\Controllers;

use Yabacon\Paystack;
use Illuminate\Http\Request;

class SubscriptionController extends Controller
{
    public function index()
    {
        // Set your Paystack API keys
        $paystack = new Paystack('sk_test_your_paystack_secret_key');

        // Set the subscription details
        $plan_code = 'my_plan_code';
        $email = 'customer@example.com';
        $amount = 10000; // in kobo
        $interval = 'monthly';

        try {
            // Create the subscription plan
            $plan = $paystack->plan->create([
                'name' => 'My Plan',
                'description' => 'Monthly subscription to My Plan',
                'amount' => $amount,
                'interval' => $interval,
                'plan_code' => $plan_code,
            ]);

            // Create the customer
            $customer = $paystack->customer->create([
                'email' => $email,
                'first_name' => 'John',
                'last_name' => 'Doe',
            ]);

            // Associate the customer with the subscription plan
            $subscription = $paystack->subscription->create([
                'customer' => $customer->id,
                'plan' => $plan->id,
            ]);

            // Pass the subscription details to the view
            return view('subscriptions.index', compact('subscription'));
        } catch (Exception $e) {
            // Handle errors
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}

In this example, the index method of the SubscriptionController creates a subscription plan, customer, and subscription using the Paystack API. It then passes the subscription details to the view, which can display a subscription form with a button that redirects the customer to the Paystack payment page. After the customer completes the payment, they will be redirected back to your website and the subscription will be activated.

Leave a comment