NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

To implement recurring subscriptions using Laravel Cashier and webhooks, you'll need to integrate Laravel's Cashier with Stripe or Paddle (depending on your choice). I'll outline the steps in detail, including code examples and explanation.

---

## Step 1: **Install Laravel Cashier**

Run the command to install Laravel Cashier for Stripe:

```bash
composer require laravel/cashier
```

For Paddle, use:

```bash
composer require laravel/cashier-paddle
```

---

## Step 2: **Set Up Stripe or Paddle**

- **Stripe**: Create a Stripe account, and get your **API keys** from the [Stripe dashboard](https://dashboard.stripe.com/apikeys).
- **Paddle**: Create a Paddle account and configure the vendor details.

Add the keys to your `.env` file:

```env
# For Stripe
STRIPE_KEY=your_stripe_public_key
STRIPE_SECRET=your_stripe_secret_key

# For Paddle
PADDLE_VENDOR_ID=your_vendor_id
PADDLE_VENDOR_AUTH_CODE=your_auth_code
PADDLE_ENV=sandbox_or_live
```

---

## Step 3: **Set Up Billable Model**

Your user model (e.g., `AppModelsUser`) should use the `Billable` trait provided by Cashier.

```php
<?php

namespace AppModels;

use IlluminateFoundationAuthUser as Authenticatable;
use LaravelCashierBillable;

class User extends Authenticatable
{
use Billable;

// Other model properties and methods
}
```

---

## Step 4: **Create Subscription Plans**

Create subscription plans in your Stripe or Paddle dashboard. These plans will have unique identifiers like `plan_monthly` or `plan_yearly`.

---

## Step 5: **Create Checkout and Subscription Logic**

You need to create a checkout process to allow users to subscribe. For Stripe:

### Route:
```php
use AppHttpControllersSubscriptionController;

Route::post('/subscribe', [SubscriptionController::class, 'subscribe'])->name('subscribe');
```

### Controller:
```php
<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

class SubscriptionController extends Controller
{
public function subscribe(Request $request)
{
$request->validate([
'payment_method' => 'required', // Stripe payment method ID
]);

$user = $request->user();

// Subscribe the user to a plan
$subscription = $user->newSubscription('default', 'plan_monthly')
->create($request->payment_method);

return response()->json(['message' => 'Subscription successful', 'subscription' => $subscription]);
}
}
```

### Blade View Example:
```html
<form action="{{ route('subscribe') }}" method="POST" id="payment-form">
@csrf
<input type="hidden" name="payment_method" id="payment-method">

<button type="submit">Subscribe</button>
</form>

<script src="https://js.stripe.com/v3/"></script>
<script>
const stripe = Stripe('{{ env('STRIPE_KEY') }}');
const elements = stripe.elements();

const cardElement = elements.create('card');
cardElement.mount('#card-element');

const form = document.getElementById('payment-form');
form.addEventListener('submit', async (event) => {
event.preventDefault();

const { paymentMethod, error } = await stripe.createPaymentMethod({
type: 'card',
card: cardElement,
});

if (error) {
alert(error.message);
} else {
document.getElementById('payment-method').value = paymentMethod.id;
form.submit();
}
});
</script>
```

---

## Step 6: **Handle Webhooks**

Cashier uses webhooks to listen to events such as subscription creation, cancellation, and payment updates.

### Configure Webhooks in Stripe:
1. Go to your Stripe dashboard.
2. Navigate to **Developers > Webhooks**.
3. Add an endpoint: `https://your-domain.com/stripe/webhook`.

### Webhook Route:
```php
use LaravelCashierHttpControllersWebhookController;

Route::post('/stripe/webhook', [WebhookController::class, 'handleWebhook']);
```

### Verify Webhook Signature:
To enhance security, verify the webhook signature:

1. Set the `STRIPE_WEBHOOK_SECRET` in your `.env` file.
2. Laravel Cashier will automatically verify the signature.

---

## Step 7: **Customize Webhook Handlers**

If you need custom logic for specific webhook events, you can extend the `WebhookController`.

```php
<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use LaravelCashierHttpControllersWebhookController as CashierWebhookController;

class WebhookController extends CashierWebhookController
{
public function handleInvoicePaymentSucceeded($payload)
{
// Handle successful payment logic
Log::info('Payment succeeded for invoice: ' . $payload['data']['object']['id']);
}

public function handleCustomerSubscriptionDeleted($payload)
{
// Handle subscription cancellation
Log::info('Subscription canceled for customer: ' . $payload['data']['object']['customer']);
}
}
```

---

## Step 8: **Test the Integration**

Use Stripe's or Paddle's test environment to ensure everything works:
1. Test subscription creation.
2. Test webhooks by simulating events from the dashboard.
3. Test failed payments and retry logic.

---

### Final Notes:
- **Webhooks** ensure your subscription system is synced with Stripe or Paddle.
- Regularly update Laravel and Cashier to maintain compatibility and security.
- For production, ensure secure configurations, including SSL and proper webhook verification.
     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.