The documentation on Laravel Cashier is quite vague and misses some very important details like what the $stripeToken is and where does it come from?
So to create a new subscription we do this:
$user->newSubscription('main', 'premium')->create($stripeToken);
This is the first time a user will be subscribing so where does $stripeToken come from exactly?
In the docs it says:
The create method, which accepts a Stripe credit card / source token,
will begin the subscription as well as update your database with the
customer ID and other relevant billing information.
Does this mean I have to manually create the customer object in Stripe first and then pass the customer id as the $stripeToken? It mentions card details but how do I pass them? What is the format and what do I expect in return?
If $stripeToken is the customer id in Stripe then Cashier is assuming that we already have customers created in Stripe which we won't have the first time.
Can anyone shed some light on this?
It turns out that the stripeToken is usually generated by stripe.js forms when they are submitted.
As I am using API driven checkout forms and not standard html submission forms I need to use the Stripe API to create the token from the card details provided.
$stripeToken = Token::create(array(
"card" => array(
"number" => $request->get('number'),
"exp_month" => str_before($request->get('expiry'), '/'),
"exp_year" => str_after($request->get('expiry'), '/'),
"cvc" => $request->get('cvc'),
"name" => $request->get('name')
)
));
Then I use $stripeToken->id and pass it:
$user->newSubscription('main', 'premium')->create($stripeToken->id);
You can use the Stripe JS to get the stripeToken but if you are using the custom form then you can use Stripe checkout method.
Using both the ways you will get stripeToken in javascript and then you have to pass this token to your REST API for further processing.
Related
I am trying to create a word-press plugin with stripe that support strong customer authentication. charges with stripe is working fine for me. I have referred this link https://www.codexworld.com/stripe-payment-gateway-integration-php/ for creating payments. Any such reference link for sca implementation in stripe? Thanks in advance
I just moved my company over from the old Charges API to SCA. It wasn't pretty. I'm a back-end engineer so I'm only going to tackle the back-end components needed to make this work. If you want a fully customised front-end too, you're going to need to read the Stripe docs and do a lot more bounces around form submit -> enhanced validation -> collect more data -> submit more data. This workflow was too complicated and thankfully my company went with the Stripe checkout solution for this part.
I work for a SaaS company and we take money for room bookings, so we have non-fungible time dependent 'stock' items. Since we sell booking slots on behalf of our customers we also have Stripe connected accounts in play. Basically, all the nightmare corner cases you could wish for. Since the checkout session is live for 24 hours we have to allocate then collect - if you start the process and then go for lunch there is no guarantee that when the payment is processed the room you want will still be free for your timeslot.
My process looks like:
Back-end calls Stripe and starts a checkout session with Session::create(). Set your payment_method_types and line_items in this as well as your return URLs. Also send up a payment_intent_data. Mine looks like this:
'payment_intent_data' => [
'transfer_data' => [
'destination' => 'acct_ number of linked account',
],
'capture_method' => 'manual',
'description' => 'description of item',
'statement_descriptor' => 'description of item, max 22 chars',
],
Obviously if you don't have connected accounts then omit the transfer_data but definitely include both descriptors. If you are sure of your stock levels (eg: digital goods) you can change your capture_method to automatic.
On a return from Stripe I send the session key (sk_) to the front-end who then hand this over to Stripe's payment form. This is the point you'll need to do a lot more work if you want a totally custom front-end. Good luck.
When the checkout session is successful I have a webhook event on checkout.session.completed to call my API, as well as handling the URL returns from the front-end. I keep extra data in my database about the payment state so I only handle each return once.
Either return leads me back to the session - the ID is in the front-end links and the session can be retrieved from $session = $event->data->object in the webhook callback. You can then get the intent out of the session with $intent = PaymentIntent::retrieve($session->payment_intent);
At this point, I handle the various status codes in the PaymentIntent;
requires_payment_method
requires_confirmation
requires_action
canceled
requires_capture
succeeded
The one I'm really interested in is requires_capture where I then check to see if the resource is still free. If it is, I $intent->capture() to finalise the payment and create the booking for the user. You can handle each of them as needed by your business process.
If you are dealing with connected accounts you will also need to load the transfer item associated with the PaymentIntent Charge object and then load the Charge referenced in the destination_payment field (you can load charges with the py_ key). Then set the description and statement_descriptor fields and save the charge back so your connected customers know what the payment is for.
Our user can enter a card to pay our services.
He/she can choose to save or to NOT save card for reusing.
When user is NOT saving card, we are creating a PaymentIntent passing
[
'amount' => floatval($this->cart->total_gross) * 100,
'currency' => 'EUR',
'payment_method' => $this->pm,
'off_session' => true,
'capture_method' => 'manual',
'confirm' => true,
];
This because it's a preauthorization of a payment that will be captured in 2-3 days.
Using this config we got the following error
Stripe\Exception\MissingParameterException - 400 - The provided PaymentMethod is already attached to another object. You cannot reuse PaymentMethods without attaching them to a Customer object first.
To be clear:
user enters a NEW CARD
choose to NOT save for future usage
stripe.js automatically handle the 3d secure card auth
the returned pm_... is sent to server with the amount and the instruction to NOT save card (so we do not create a stripe customer)
using the above config we call the \Stripe\PaymentIntent::create method
we got the error above
What is the meaning of this error? Why does it says that the PM is already attached to another object? Which? Of which kind?
I triple-checked my code and it's the ONLY api call we are making after receiving the pm from frontend.
And the frontend, previously, simply use a setupIntent to authorize the card using official stripe.js calls. So the pm, returned from stripe.js is sent to our server without doing nothing with it. And our server simply call the create method, and got this error every time.
Asking your help to diagnose and understand.
We're using latest official stripe-php versions
Thanks in advance
I finally received an official response on this problem.
Simply: we cannot save a card for of_session payments and then use the payment method in a later moment to capture the pre-authorized amount
So, we modified our flow
User choose or save a card and we inform the user that we must save the card to be able to reuse to complete the payment flow.
I am trying to retrieve various pieces of data from a Stripe Checkout form submission, where I am just using the Stripe Checkout code provided in my Stripe Dashboard.
In my checkout_submission_completed event I have webhook where I am trying to retrieve email, name so that after successful purchase I can take other actions.
It is surprisingly difficult.
Here is how I can retrieve email (where payload is the response my webhook receives):
$cust = $payload['data']['object']['customer'];
$custdata = \Stripe\Customer::retrieve($cust);
$email=$custdata->email;
Ok, not a big deal.
How about Name? Well, here is where things get really fun. After hitting the form payment submit button Stripe creates a customer, completes a successful charge. But in the Customer object there is no name. Yes, no name. During a chat today with Stripe they had no explanation and said they would look into it more.
Turns out the only place where the name entered on the form shows up in a Stripe object is the Payment Details Object within the Payment Intent object.
I am serious. So here is how I am getting the name (using cust from previous code:
$piid = $cust = $payload['data']['object']['payment_intent'];
$pi = \Stripe\PaymentIntent::retrieve($piid);
$name = $pi['charges']['data'][0]['billing_details']['name'];
Is there a better way for me to do this?
thanks,
Brian
I think the idea is that the name collected is a cardholder name and is associated with the card [0] , not the Customer. A Customer might end up with multiple cards or other payment methods, and they might reasonably all have different cardholder names. So that information isn't transposed up to the Customer by default.
Your approach looks generally good — I would personally use the expand feature [1] of the API so you can skip a bunch of API calls by retrieving the full context of the Checkout Session and its payment and customer in one call from the webhook handler.
$session = \Stripe\Checkout\Session::retrieve(
$payload['data']['object']['id'],
["expand" => ["payment_intent", "customer"]]);
$cardholderName = $session['payment_intent']['charges']['data'][0]['billing_details']['name'];
\Stripe\Customer::update($session['customer'].id,
["name" => $cardholderName]);
[0] - https://stripe.com/docs/api/payment_methods/object?lang=php#payment_method_object-billing_details-name
[1] - https://stripe.com/docs/api/expanding_objects?lang=php
I have successfully created a subscription using Laravel Cashier however I have a problem regarding the payouts.
My use case is that I collect the amount from the user in a form of a subscription and then after specific action of the user, a certain amount is transferred further to the vendor.
I am using Manual Transfers for payouts and it seems it has everything I need (https://stripe.com/docs/connect/charges-transfers).
However in order to create a transfer from one Stripe account to another I have to assign a field "transfer_group" to my charge. Since I'm not using Charge for my subscriptions but Cashiers methods I don't have this option.
Looking into the implementation of "newSubscription" method or "create" method inside Billable class I couldn't find anything where I could pass this.
Can this be achieved or I have to reimplement my subscription using plain Stripe SDK?
Here's how my subscription code looks like:
$response = $customer->newSubscription($plan->name, $plan->plan_id)->create($request->token, [
'email' => $user['profile']['email'],
'description' => $user['profile']['biography'],
'metadata' => [
'name' => $user['profile']['name'],
'uuid' => $request->uuid
]
]);
All these options passed here are related to a Customer object and not Charge. According to Stripe docs I need something like:
$charge = \Stripe\Charge::create(array(
"amount" => 10000,
"currency" => "eur",
"source" => "tok_visa",
"transfer_group" => "{ORDER10}",
));
Since you don't control the charge creation here, you won't be able to pass transfer_group. What you should do instead is pass source_transaction: "ch_XXXX" when you create the transfer via the API. This will ensure that the Transfer is associated with the charge associated with the subscription and suit Stripe's requirements.
This is documented directly in Stripe docs here.
I have set up subscription based website that allows people to have multiple subscriptions. I decided to go with Stripe for payment and card processing. It took very little time to get it integrated into my Symfony2 project. I was able to create subscriptions, customers, and add cards within a couple of hours. Then I ran into an issue. If a customer has multiple cards, I wanted to be able to allow them to choose which card they wanted to use when they create a new subscription. It sounded easy. After 2 days and about 30 hours of combing through their documentation I have to say that I cannot figure out how to get this to work.
The way I have this set up is that when the customer creates a card I store the "card id" in my database along with the brand. This just makes it easy to load details on the server side when the page is being requested. The customer creating the new subscription sees their cards and choose which one they want to use for the new subscription. This is passed to my php script via AJAX to create the new subscription. However, when I try to use a specific card, I am getting a 400 error indicating that the "card id" is not a token. I know that it is not a token since the token was used to add the card to the customer account but how in the world do I specify the exact card that the customer wants to use?
NOTE: Using an a new token creates another instance of the card.Not an option.
PHP:
require_once('../stripe-php/init.php');
//Set Secret API Key
\Stripe\Stripe::setApiKey("sk_test_XXXXXXXXXXXXXXXXXXXXX");
//Retrieve Customer
$cu = \Stripe\Customer::retrieve($_POST['customer_id']);
//Create Subscription using saved customer "card id"
$createSubscription = $cu->subscriptions->create(array("plan" => $_POST['sub_option'], "source" => $card));
POSTED TO STRIPE:
plan: "500-2016"
source: "card_xxxxxxxxxxxxxxxxxxxxx"
STRIPE ERROR: TYPE 400
error:
type: "invalid_request_error"
message: "No such token: card_xxxxxxxxxxxxxxxxxxxxxxx"
param: "source"
I got a reply from Stripe support on this: it is not possible for one Customer to have subscriptions with different payment sources. All invoices for subscriptions are always billed to the current default_source for the Customer. So if you change the default as Giles Bennett suggested, you'll be changing it for all subscriptions, regardless of what the default was at time of creation.
If you need one user to have subscriptions with more than one source, you need to create multiple stripe Customer objects for that user, with a different default_source for each.
Since I have not received any input from SO or Stripe, I have somewhat came to the conclusion that this cannot be done. I found a similar question on a different forum that ended with the results being - No Response From Stripe - and that this cannot be done. Though the Stripe documentation does not hit on this subject it does appear that a Subscription can only be charged to the default card. There is no "Card" object for subscriptions as there is for a "Charge".
I realise this thread is quite old, but having come across it whilst trying to answer the same question myself, this solution may be of use to those who come along afterwards.
The Stripe API says that the "source" parameter for the API call to create a new subscription is optional - if ommitted, then it will default to the customer's default card. If included, then it can only be a token (ie. a new card) or a dictionary entry (again, for a new card, just not tokenised).
The solution could be to update the customer's default source first. Using Cartalyst through Laravel, as we are :
$customer = Stripe::customers()->update( "customer_id", [
'default_source' => "card_id"
]);
You can then proceed to add your subscription as normal - the newly-defaulted card will be assigned to it. If needs be (depending on your application) then you may also wish to save the previous default card ID to a variable first, to then allow you to set it back to being the default card after your new subscription.
I hope that helps.