Search code examples
laravelstripe-paymentslaravel-cashier

Laravel Cashier auto send email on invoice / receipt


On Stripe document / Laravel cashier it says it can send email automatically after invoice was created. I tried to switch the settings related on that on Stripe's settings menu, but I am not receiving any email after I purchase or subscribe. Do I still need to manually code the email sending? ( I am thinking that it should be automatically sent after invoice was created )


Solution

  • According to Stripe docs, if you want Stripe to automatically send receipts, You have to set customer’s email parameter when creating a subscription and ensure that the option email customers for successful payments is enabled on Stripe dashboard

    $user->newSubscription('default', 'monthly')
        ->create($paymentMethod, [
            'email' => $user->email, // <= customer’s email
        ]);
    

    Please note that:

    Receipts for payments created using your test API keys are not sent automatically. Instead, you can view or manually send a receipt using the Dashboard.


    But if you want to send receipts by Laravel instead, You can define a new webhook event handler and use Stripe webhook:

    1. Set up a new endpoint at Stripe dashboard to https://your-domain.com/stripe/webhooks

    2. List the URI as an exception in your VerifyCsrfToken middleware or list the route outside of the web middleware group:

      protected $except = [
          'stripe/*',
      ];
      
    3. Define a new WebhookController and add a handleInvoicePaymentSucceeded method to the controller to handle the invoice.payment_succeeded webhook:

      <?php
      
      namespace App\Http\Controllers;
      
      use Laravel\Cashier\Http\Controllers\WebhookController as CashierController;
      use App\Notifications\InvoicePaid;
      
      class WebhookController extends CashierController
      {
          /**
           * Handle payment succeeds.
           *
           * @param  array $payload
           * @return \Symfony\Component\HttpFoundation\Response
           */
          protected function handleInvoicePaymentSucceeded(array $payload)
          {
              $invoice = $payload['data']['object'];
              $user = $this->getUserByStripeId($invoice['customer']);
      
              if ($user) {
                  $user->notify(new InvoicePaid($invoice));
              }
      
              return new Response('Webhook Handled', 200);
          }
      }
      
    4. Define a route to your Cashier controller within your routes/web.php file. This will overwrite the default shipped route:

      Route::post('stripe/webhook', '\App\Http\Controllers\WebhookController@handleWebhook');
      
    5. (Optional) You can manually set Stripe's webhook signatures for more security.

    See Laravel docs form more info.