Laravel Cashier Webhook: Get Amount and Invoice Details - laravel

I am using Laravel 5.3 with Cashier for Stripe. I have set-up a custom controller extending the CashierController for handling Webhooks as per the Docs. In this Webhook, how can I get the amount that was charged and invoice details from $payload?
public function handleInvoicePaymentFailed($payload)
{
// Handle The Event
$customer = $this->getBillable($payload['data']['object']['customer']);
// NEXT - HOW TO GET THE AMOUNT THAT WAS CHARGED AND INVOICE NUMBER??
return new Response('Webhook Handled', 200);
}
I want to get the following info from that:
Amount
Invoice Number

You should be able to use $payload['data']['object']['amount_due'] to get the amount due and $payload['data']['object']['id'] to get the stripe invoice id.
Go to https://dashboard.stripe.com/test/events, click on the event and look at the Event Data there.

Related

Laravel websocket to broadcast periodically

I would like to know if there's other appropriate way to achieve below in Laravel ~7.
Purpose: To update fast-selling product quantities every minute on the frontend (client) in real time.
Method: Use a scheduler to get the product quantity from the database and use websocket to broadcast it every minute.
Question: Is there any other better way to achieve this?
Event broadcast (backend)
// app/Events/ProductQuantity.php
class ProductQuantity implements ShouldBroadcast
{
public $product;
public function __construct(Product $product)
{
$this->product = $product;
}
public function broadcastWith()
{
return ['quantity' => $this->product->quantity];
}
public function broadcastOn()
{
return new Channel('store');
}
}
StoreFrontend (client)
<script>
Echo.channel('store')
.listen('ProductQuantity', (e) => {
console.log(e.quantity);
})
</script>
Possibly...
Currently it sounds like you are effectively "polling" your database for the quantity of a product and then emitting this to your frontend with websockets.
This is no different from using traditional polling techniques to hit an endpoint and request the latest quantity.
A better solution, in my opinion, would be to raise an event whenever the quantity of your product changes (either sold or stock is replenished). You can then hook this event up to broadcast to your frontend.
The result is that your frontend is notified whenever the stock changes, as opposed to needlessly polling every minute. It gives you the benefit that you don't need to hammer your database every minute on the scheduler to see if any data has changed, and the ability to immediately update your UI whenever the stock for a product changes.

How to Cancel the Braintree Subscription by Braintree_id or subscription_id using Laravel Cashier

We are using Laravel Cashier (Braintree) with Laravel version 5.8. We have a case where a user is subscribed to same plan with same name multiple times for different orders.
We want to give the ability to user to cancel their subscription.
we tried below statement to cancel the subscription with subscription name as suggested by manual here https://laravel.com/docs/5.8/braintree#cancelling-subscriptions.
$user->subscription('main')->cancel();
$user->subscription('main')->cancelNow();
We are passing the subscription name. It works fine as expected and also updating the date in "ends_at" column of subscription table.
The problem here is that as we have same name for the subscriptions where user is subscribed to. So in our case it returns the last subscribed order here and cancel that. It's fine as what it is suppose to do.
But we want to cancel the subscription based on braintree_id stored in subscriptions table. Can we do that ?
As of now we tried it like below:-
use Braintree\Subscription;
$subcriptionObj = Subscription::find($subscription); //where $subscription is braintree_id from subscriptions table.
if ($subcriptionObj->status == 'Canceled')
abort(400, 'Subscription Not Active');
Subscription::cancel($subscription);
This however cancel the subscription at Braintree but not updating the column "ends_at" in subscriptions table.
Can anyone suggests a workaround for this ? Any help would be appreciated.
Since the Laravel Braintree Cashier module is internally using Braintree Subscription library. So I thought to use the same directly into my controller.
I used namespace into my controller for subscription to call the Braintree subscription class directly. the below is the code to cancel the subscription by subscription ID.
use Braintree\Subscription;
public function cancelsubscription(User $user, $subscriptionId)
{
$subcriptionObj = Subscription::find($subscriptionId);
if(is_null($subcriptionObj)){
abort(400, 'Subscription is not found.');
}
if ($subcriptionObj->status == 'Canceled')
abort(400, 'Subscription is not Active.');
// In below line we are finding the Subscription DB Obj using cashier module here to update the ends_at date column
$subsDbObj = $user->subscriptions->filter(function($sub) use ($user,$subscriptionId){
return $sub->braintree_id == $subscriptionId && $sub->user_id == $user->id;})->values();
Subscription::cancel($subscriptionId);
if(! is_null($subsDbObj[0])){
//Internally cashier module doing the same to update the subscription table
$subsDbObj[0]->ends_at = Carbon::now();
$subsDbObj[0]->save();
}
return 'Cancelled';
}

Get next billing date from Laravel Cashier

I have subscribed a user to a subscription plan through Laravel's Cashier package. I now want to display the date the user will next be billed, however this doesn't appear to be an available through the Billable trait.
How do I get the next billing date?
Thanks!
The solution is to use the asStripeCustomer method:
// Retrieve the timestamp from Stripe
$timestamp = $user->asStripeCustomer()["subscriptions"]->data[0]["current_period_end"];
// Cast to Carbon instance and return
return \Carbon\Carbon::createFromTimeStamp($timestamp)->toFormattedDateString();
Note that I've only tested this with a user who has a single subscription - data[0].
You may need to alter this code for multiple subscriptions or if the user has cancelled and started another subscription.
Building on previous answers, here's what's working for me:
private function getSubscriptionRenewDate($plan)
{
$sub = Auth::user()->subscription($plan)->asStripeSubscription();
return Carbon::createFromTimeStamp($sub->current_period_end)->format('F jS, Y');
}
Subscriptions also have a ->asStripeSubscription() method that gives you access to the values just for that subscription. So you could do:
// Retrieve the timestamp from Stripe
$timestamp = $subscription->current_period_end;
// Cast to Carbon instance and return
return \Carbon\Carbon::createFromTimeStamp($timestamp)->toFormattedDateString();

Laravel Cashier Re-attempt Pending Invoice after Card Updates

I am using Laravel 5.3 with Cashier. If a customer updates their card details, how can I check if there is a pending invoice and ask Stripe to re-attempt the charge on the new card? At the moment, I have set the settings for attempts in Stripe dashboard. But from what I understand, Stripe does not automatically attempt to charge the customer if they updated their card details and it waits for the next attempt date to try again. Thats why I want to manually attempt to charge the customer on pending invoice as soon as they update their card. I read the Cashier documentation and Github page but this case is not covered there.
$user->updateCard($token);
// Next charge customer if there is a pending invoice
Can someone help me out please.
After testing and talking with Stripe support, I found out the problem with the current updateCard() method used in Laravel Cashier.
With the current updateCard() method, the card is added to the sources list and then sets the new card as the default_source. the result of this method has 2 outcomes:
Multiple cards gets added to the list although the recent one is set as default_source
When updating the card using this method, if there are any unpaid invoices (i.e. invoices in past_due state), they are not automatically charged.
In order for stripe to re-attempt charging customer on all invoices in past_due state, the source parameter needs to be passed. So I have created a new method something like this:
public function replaceCard($token)
{
$customer = $this->asStripeCustomer();
$token = StripeToken::retrieve($token, ['api_key' => $this->getStripeKey()]);
// If the given token already has the card as their default source, we can just
// bail out of the method now. We don't need to keep adding the same card to
// a model's account every time we go through this particular method call.
if ($token->card->id === $customer->default_source) {
return;
}
// Just pass `source: tok_xxx` in order for the previous default source
// to be deleted and any unpaid invoices to be retried
$customer->source = $token;
$customer->save();
// Next we will get the default source for this model so we can update the last
// four digits and the card brand on the record in the database. This allows
// us to display the information on the front-end when updating the cards.
$source = $customer->default_source
? $customer->sources->retrieve($customer->default_source)
: null;
$this->fillCardDetails($source);
$this->save();
}
I have created a Pull request for this addition. Since editing the Billable file directly for any changes is not a good idea, if this doesnt get added to Cashier, then you can use the following in the Controller file to do it directly from there:
$user = Auth::User();
$customer = $user->asStripeCustomer();
$token = StripeToken::retrieve($token, ['api_key' => config('services.stripe.secret')]);
if (!($token->card->id === $customer->default_source)) {
$customer->source = $token;
$customer->save();
// Next synchronise user's card details and update the database
$user->updateCardFromStripe();
}

Starting a no card up front subscription using Laravel Cashier & Stripe

I'm confused about how Cashier/Stripe subscriptions work with no card up front trials.
I have set the trial period on Stripe and created the plans.
I have set the no card up front model trait to false.
$user = User::find(1);
// This doesn't seem to do anything. No sub created in Stripe.
$user->subscription('yearly_uk');
// This throws an error as I am not passing through a card token.
$user->subscription('yearly_uk')->create();
// This throws an nasty api error but strangely does create a customer in Stripe.
$user->subscription('yearly_uk')->create(null);
Any ideas?
By your comment, it looks like you've already answered this, but for future readers, I encountered a similar problem where the user can choose from a few plans, one of which is free.
To resolve, add this to your User Model:
protected $cardUpFront = false;
protected $trial_ends_at = null;
then you can subscribe the user using a null token:
$user->subscription('yearly_uk')->create(null);
I haven't checked, but I assume it won't throw the same kind of errors if / when you move to a paid plan - i.e. they'll be able to change, but I would guess Stripe will return an error as it'll bill the user with no credit card details.
\Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$user_id = Auth::user()->id;
$AuthUser = Auth::user();
$stripe_plan = 'plan_CMFx07YJ96oL6h'; //Free stripe plan
$user = User::find($user_id);
$user->newSubscription('main',$stripe_plan)->create(null);
if($AuthUser->subscribed('main')){
return redirect('subscription')->with('status','You are subscribed successfully.');
}

Resources