Stripe-Api: How to get the "PaymentMethod" (ID) from the Customer Object? - php

Before the Strong Customer Authentication (SCA), I could get the sources collection from the Customer Object with $customer->sources['data']
Now I'm trying to migrate to SCA, but cannot figure out how I can get my "paymentMethod" via the customer object without saving it to the database.
Here is the documentation again: https://stripe.com/docs/payments/cards/saving-cards#save-payment-method-without-payment
But to make it short, I save the "paymentMethod" like this:
// This creates a new Customer and attaches the PaymentMethod in one API call.
\Stripe\Customer::create([
'payment_method' => $intent->payment_method,
]);
However, the Payment-Method-ID is not publically reachable with the customer object.
Is it possible to get it somehow?

PaymentMethods are not embedded on the Customer object itself and don't appear in $customer->sources. Instead, you can for example list them using the API [0] or retrieve directly given an ID(that you might also save in your database associated with the customer ID along with your user information).
$customer = \Stripe\Customer::create([
'payment_method' => $intent->payment_method,
]);
$cards = \Stripe\PaymentMethod::all([
"customer" => $customer->id, "type" => "card"
]);
/*
OR
*/
$card = \Stripe\PaymentMethod::retrieve($intent->payment_method);
[0] - https://stripe.com/docs/api/payment_methods/list

Related

Laravel Stripe MultiPlan Subscription

I want to add Add On to my subscription. Thus i follow this MultiPlan in Laravel doc. For every new subscription, new stripe product are create (means every plan have different product. including the addon). User need to subscribe to any subscription before subscript to the addon. There are no error, but the Subscription DB from stripe for the current subscription will return null quantity and null stripe_plan. Then create error from that database as i cant call the current subscription. Why does the stripe does that? or am I surpose to create new plans under the same product id in Stripe?
My code to create stripe product and plan
$stripe = new StripeClient(env('STRIPE_SECRET'));
$product_stripe = $stripe->products->create([
'name' => $request->service_name,
]);
$plan_stripe = $stripe->plans->create([
// 'id' => $stripe_plan,
'nickname' => $request->service_name,
'product' => $product_stripe['id'],
'amount' => $request->price*100,
'currency' => 'usd',
'interval' => $request->period,
'interval_count' => $request->period_num,
]);
This is my code to subscribe to addon
$user = auth()->user();
$user->subscription('default')->addPlanAndInvoice('plan_stripe_id', 'quantity');
Note that default is the user current subscription.

Stripe - Upgrade/downgrade plan response in webhook

Following code I'm using to upgrade a user's plan:
$subscription = \Stripe\Subscription::all(array('customer'=>$customerId,'limit'=>10));
$subscription_id = $subscription->data[0]->id;
$subscription = \Stripe\Subscription::retrieve($subscription_id);
$updatePlan = [
'cancel_at_period_end' => false,
'items' => [
[
'id' => $subscription->items->data[0]->id,
'plan' => planPrefix.$packageId,
],
],
'tax_percent' => $package_tax,
];
\Stripe\Subscription::update($subscription_id, $updatePlan);
//Create invoice now
$invoice = \Stripe\Invoice::create([
'customer' => $customerId,
]);
$invoiceId = $invoice->id;
//Pay invoice now
$invoice = \Stripe\Invoice::retrieve($invoiceId);
$invoice->pay();
And when stripe get paid to that newly created invoice, The event "invoice.payment_succeeded" is triggered to my webhook where I update my database accordingly.
The problem is that stripe sends me previous plan id with the accurate invoice.
E.g., If User A subscribes to plan id 1 then stripe sends me object for the newly subscribed plan details to my webhook with accurate data, but when User A
upgrades to plan whose id is 2, stripe sends me data with the event of "invoice.payment_succeeded" where I can find all the data related to subscription update but the issue is with the plan id. The plan id stripe sends me is old one i.e., 1 instead of 2, and when User A upgrade to plan id 3 then it sends me plan id 2 in the webhook notification.
Any help in this matter would be much appreciated.

Get last 4 digits of credit card after successful Stripe subscription

For compliance reasons I am generating tokens on the client side and sending those details to stripe. I want to display the last four digits and the type of card on my confirmation page
I am creating a customer
// Create a Customer:
$customer = \Stripe\Customer::create([
'source' => $token,
'email' => $current_user->user_email,
]);
than adding them to a subscription
//create the subscription for the customer
$subscription = \Stripe\Subscription::create(array(
'customer' => $customer->id,
"items" => array(
array(
"plan" => "dpc-standard",
),
)
));
The subscription returns https://stripe.com/docs/api#subscription_object
a ton of data including the invoice_id that is generated for the subscription but doesn't return any CC details
When you create a Customer and pass the source parameter set to a token id, it will save that card on the new customer. The value returned by this call is a Customer object with the sources property which will contain the new card you just saved.
You can access the last 4 digits easily using:
$last4 = $customer->sources->data[0]->last4;

How to get the charge ID from Stripe using PHP?

First of all, I am aware that this question has been asked but they didn't explain how to get the information using
charge.succeeded
I am creating an auth and capture charge using Stripe. I need the charge ID to confirm/capture the charge.
The following code creates the charge but doesn't charge until it's been approved.
\Stripe\Charge::create(array(
"amount" => $price,
"currency" => "usd",
"customer" => $custID, // obtained with Stripe.js
"description" => "Charge for test#example.com",
"capture" => false
));
I assumed that I could get the charge ID by doing:
$chargeID = $charge->id;
because that's how I get the customer ID when I create a customer. But I get nothing when I echo out the variable, which doesn't help since I want to save it in a database. I've looked everywhere but can't find anything concrete or recent.
Then to complete the charge. I have to capture it this way:
$ch = \Stripe\Charge::retrieve("$chargeID");
$ch->capture();
This is all from the Stripe API Reference but it doesn't explain how to get the charge ID. It doesn't even tell you how to get the customer ID, luckily Stack Overflow came through with that one.
This is all done using PHP.
According to Stripe's Documentation, when creating a new charge you get Stripe\Charge JSON object in return (or an exception if something went wrong).
You can var_dump the object you just created to see what your object looks like, but according the the API you can use the id of the returned object:
$charge = \Stripe\Charge::create(array(
"amount" => $price,
"currency" => "usd",
"customer" => $custID, // obtained with Stripe.js
"description" => "Charge for test#example.com",
"capture" => false
));
// you can use the var_dump function to see what's inside the $charge object
// var_dump($charge);
$chargeID = $charge->id;
(And you don't need to call the Charge::retrieve again, you can use the current $charge object).

Laravel Cashier - Create New Subscription With Existing Customer Object

I'm using Laravel Cashier along with Stripe to manage subscriptions. The user will supply their credit card information when signing up, but they won't be subscribed in a specific plan at this point. So I can successfully use Stripe Checkout to create a Stripe customer object and save the Stripe customer ID in my database. But when it comes time for the user to enroll in a plan, I can't see a way to use the Stripe customer ID to enroll them in the plan they want.
Of course, I could ask for their credit card information again and get a Stripe token to use with Laravel Cashier, but I'd like to avoid this since the app already created a Stripe customer object when they signed up and I'd like to simply use the existing customer object to charge their credit card rather than asking for their card number again.
To try illustrate what I'm trying to do, here is some sample code from the Laravel docs:
$user->newSubscription('main', 'monthly')->create($creditCardToken);
But what I'd like to be able to do is something like this (note the change to the create method:
$user->newSubscription('main', 'monthly')->create($user->stripe_id);
Any advice?
If there is a stripe ID for the user, you don't have to supply the token
$user->newSubscription('main', 'monthly')->create();
Have a look at the SubscriptionBuilder class.
You can try this.
$user->setStripeKey(env("STRIPE_KEY"));
# card details
$card = [
'card_number' => 'xxxxxxxx',
'card_cvc' => 'xxx',
'exp_month' => 'xx',
'exp_year' => 'xxxx',
'name' => 'xxx',
];
# generate token
$token = $this->generateAccessToken($card);
private function generateAccessToken($card)
{
$client = new \GuzzleHttp\Client();
$url = 'https://api.stripe.com/v1/tokens';
$pubKey = env("STRIPE_SECRET");
$postBody = [
'key' => $pubKey,
'payment_user_agent' => 'stripe.js/Fbebcbe6',
'card' => [
'number' => $card['card_number'],
'cvc' => $card['card_cvc'],
'exp_month' => $card['exp_month'],
'exp_year' => $card['exp_year'],
'name' => $card['name']
]
];
$response = $client->post($url, [
'form_params' => $postBody
]);
$response_obj = json_decode($response->getbody()->getContents());
return $response_obj->id;
}
# main or primary
$subscription_obj = $user->newSubscription('subscription_name', 'stripe_plan_id')->create($token);

Categories