How to update credit card payment in stripe - node.js

I have a flow using nodejs and reactjs to let users subscribe to my site.
So when user logs in he can see a few packages.
When the user selects a package and enters card details, I do the following:
1 - Create a new customer, based on user details (name, email etc, fetched since user logged in)
2 - Create a subscription for the newly create customer according to price_id selected
3 - Collect in the frontend the card number/cvc/expire date with:
const cardElement = elements.getElement(CardElement);
4 - Make a call to stripe from frontend with:
const { error, paymentIntent } = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: cardElement,
billing_details: {
name: name,
}
}
});
Im not sure if this was the best flow. However, it is working.
I also managed updating subscription and canceling it.
However, Im having an hard time in changing credit card details.
What I understood from docs I should use the same call as I did when I create the card payment.
So I collect again the credit card number and call again the same function:
const { error, paymentIntent } = await stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: cardElement,
billing_details: {
name: name,
}
}
});
However, the call is done to:
https://api.stripe.com/v1/payment_intents/pi_XXXX/confirm
and returns a 400 with this info:
type: "invalid_request_error", code: "payment_intent_unexpected_state", doc_url: "https://stripe.com/docs/error-codes/payment-intent-unexpected-state"
Should I use something else to update credit card info? Or am I calling it in the wrong way?

Your initial flow of calling confirmCardPayment() is correct, that is what is recommended in Stripe's docs too: https://stripe.com/docs/payments/accept-a-payment?platform=web&ui=elements.
hard time in changing credit card details. What I understood from docs I should use the same call as I did when I create the card payment.
To just collect card details and create a PaymentMethod, you should call createPaymentMethod() [0] from Stripe.js. That will convert a customer's card into a PaymentMethod like pm_123.
You will then send that PaymentMethod to your backend server, where (using your server-side Stripe API library like stripe-node) you'll attach it to a Stripe Customer [1] and also update as the Customer's default PaymentMethod for recurring payments [2].
[0] https://stripe.com/docs/js/payment_methods/create_payment_method
[1] https://stripe.com/docs/api/payment_methods/attach
[2] https://stripe.com/docs/api/customers/update#update_customer-invoice_settings-default_payment_method

Related

Saving credit card of a Custom Account's customer in Stripe

We are building a Platform.
In our Platform we create Custom Connect Accounts in Stripe.
For these Custom Connect Account we create customer accounts. Essentially the customer accounts are end-customers of our Custom Connect (Company)accounts in the Platform.
Now we would like to store credit card information of the customer accounts (for a particular custom connect account).
We followed the instructions here to create a setupIntent. The code is as below, here the stripe_account is the account_id of the custom connect (Company) account and customer['id'] is the id of the customer account -
intent = stripe.SetupIntent.create(
customer=customer['id'],
stripe_account = stripe_account
)
We pass this intent.client_secret to our front end. In the Javascript we are calling this -
setupForm.addEventListener('submit', function(ev) {
ev.preventDefault();
stripe.confirmCardSetup(
clientSecret,
{stripe_account : stripe_account},
{
payment_method: {
card: cardElement,
billing_details: {
name: cardholderName.value,
},
},
}
).then(function(result) {
if (result.error) {
// Display error.message in your UI.
} else {
// The setup has succeeded. Display a success message.
}
});
});
But we are getting the error, No such setupintent: 'seti_1IBkyZ4ZQzThevDR3MR433aI'. Clearly the setupintent that was generated from Stripe is not being accepted here. What are we doing wrong?
The likely cause of this error is that you're not initializing Stripe.js with the stripeAccount the Setup Intent exists on. Your Stripe.js initialization code should look something like this:
var stripe = Stripe('pk_test_YOUR_PUBLISHABLE_KEY', {
stripeAccount: 'acct_CONNECTED_ACCOUNT_ID'
});
That will allow Stripe.js to make requests on behalf of the connected account (which is where the Setup Intent exists).

stripe.confirmCardSetup not attaching card to customer

I'm using expressjs with sapper/svelte on the front.
I'm attempting to use stripe SetupIntent api and stripe.confirmCardSetup to save card details and attach it to a customer for future charges. I believe after reading the documentation I understand the flow of the process and my code is based on their example from the custom payment flow section
After submitting the credit card form, I get nothing. No card attached to the customer, no console log output and no errors in my application. The setupIntent is successfulLY created and I'm able to view it in my stripe dashboard but no card (paymentMethod) is created and attached to the customer. Here is my steps:
1- When a user create an account, I create a customer in stripe and
save the stripe customer's id in my db
2- I use that stripe customerid to create a setupIntent on the server
const intent = stripe.setupIntents.create({
customer: customer
}).then(intent => {
return res.end(JSON.stringify({ info: intent.client_secret }));
});
At this stage, I need the client_secret to use it on the front with my card-element to submit the card details securely to stripe.
I confirm the setupIntent is indeed in my stripe dashboard. So this part is fine.
Now to the front part of my code :
I get the client_secret on the front of my application and use stripe.js to collect and submit the card details to be attached as a paymentMethod to the customer (which the client_secret has the customer.id), so the code is :
let clientsecret
let stripe = null
let cardelement = null
stripe = await loadStripe('pk_test_mykeys');
var elements = await stripe.elements();
cardelement = await elements.create('card');
cardelement.on('ready', ()=>{});
cardelement.on('change', ({error}) => {
const displayError = document.getElementById('card-errors');
if (error) {
displayError.textContent = error.message;
} else {
displayError.textContent = '';
}
}); //end of card.on fn
cardelement.mount("#card-element");
return{
stripe : stripe,
cardelement : cardelement
}
function clickhandle(){
stripe = stripe
stripe.confirmCardSetup( csec , {
payment_method: {
card: cardelement,
billing_details: { user : "testing setupIntent"
}
},
setup_future_usage : 'on_session'
})
.then(function(result) {
if (result.error) {
console.log("there is an error")
}
if(result.setupIntent){
console.log("here is the setupintent success result")
}
});
}
Stripe.js works because I tested a paymentIntent and charging credit card on a different part of the application and the executed charges are showing in the stripe dashboard, so it is not the stripe.js script.
Is my process flow correct? Use stripe customer id to create setupIntent on my server and on the front the above code which collects card details and submit it using stripe.confirmCardSetup which will attach the paymentMethod/card details to the customer from the setupIntent client_secret?
Any help would be appreciated as I read the documentation and it is clear and straightforward. I followed it step by step. What am I missing?
The correct process is described here: https://stripe.com/docs/payments/save-and-reuse#web-create-setup-intent and you're doing things a bit different that may be causing some issues.
I suspect that your inclusion of future_usage - which isn't actually a parameter to that function call - is likely the problem.
After reading #floatingLomas comments, I went back and read carefully the documentation again. Here are the issues that need to be clear:
1- the form where you will mount the #card-elements needs to include the client_secret, whether in a hidden field or using data- attribute.
read here if you don't know about it
So --note the data-secret attribute --my form code now is :
<form data-secret={customersecret} on:submit={stripehandle} id="payment-form">
<label for="card-element">Enter Your Credit Card Details:</label>
<div id="card-element"></div>
<div id="card-errors" role="alert"></div>
<button id="submit">Pay -svelte2 component</button>
</form>
2- remove future_usage as #floatingLomas suggested. The correct parameter is "Usage" : "on_session" because the future_usage is for the paymentMethod api not the setupIntent api
3- The parameter billing_details: { "user" : "testing setupIntent" } was wrong.
The api has parameter for name, phone, address but not user ;)
So the confirmCardSetup() code is the following:
stripe.confirmCardSetup( csec , {
payment_method: {
card: cardelement,
billing_details: { "name" : "testing setupIntent" }
}
})
.then(function(result) {
console.log("result :", result)
})

How to retrieve the Stripe fee for a payment from a connected account (Node.js)

I've been reading the documentation for how to retrieve the Stripe fee from a given payment here:
// Set your secret key. Remember to switch to your live secret key in production!
// See your keys here: https://dashboard.stripe.com/account/apikeys
const stripe = require('stripe')('sk_test_xyz');
const paymentIntent = await stripe.paymentIntents.retrieve(
'pi_1Gpl8kLHughnNhxyIb1RvRTu',
{
expand: ['charges.data.balance_transaction'],
}
);
const feeDetails = paymentIntent.charges.data[0].balance_transaction.fee_details;
However I want to retrieve the Stripe fee for a payment made to a connected account. If I try the code above with a payment intent from a linked account I get the error:
Error: No such payment_intent: 'pi_1Gpl8kLHughnNhxyIb1RvRTu'
However, I can actually see the payment intent listed when I receive the posted data from the webhook:
{ id: 'evt_1HFJfyLNyLwMDlAN7ItaNezN',
object: 'event',
account: 'acct_1FxPu7LTTTTMDlAN',
api_version: '2019-02-11',
created: 1597237650,
data:
{ object:
{ id: 'pi_1Gpl8kLHughnNhxyIb1RvRTu',
object: 'payment_intent',
Any tips?
I want to retrieve the Stripe fee for a payment made to a connected
account. If I try the code above with a payment intent from a linked
account I get the error:
In order to retrieve the Stripe fee for a payment made on behalf of a connected account (using a direct Charge) you need to make the retrieve request as the connected account by specifying the special Stripe-Account header in the request. When using stripe-node we'll add that header for you automatically if you pass in the account ID as part of the request options. For example:
const paymentIntent = await stripe.paymentIntents.retrieve(
"pi_1HCSheKNuiVAYpc7siO5HkJC",
{
expand: ["charges.data.balance_transaction"],
},
{
stripeAccount: "acct_1GDvMqKNuiVAYpc7",
}
);
You can read more about making requests on behalf of connected accounts in stripe-node and our other libraries here: https://stripe.com/docs/api/connected_accounts

create charge for existing customer with different card

So i have a customer which already has a card created.
On the frontend, i give the option to use the existing card or a different one.
Following the API docs, for the new card, i create the token, send it to my backend...
In the backend:
const paymentInfo = {
customer: customerId,
amount: Number(total) * 100,
currency: 'usd',
source: existingCardId || token
}
const charge = await stripe.charges.create(paymentInfo)
If i pay with the existing card, the charge goes through, but if i send a new token, I get an error back:
Customer cus_G4V0KvxKMmln01 does not have a linked source with ID tok_1FYMLTAOg97eusNI2drudzlJ.
From the API Docs:
https://stripe.com/docs/api/charges/create
source optional A payment source to be charged. This can be the ID of
a card (i.e., credit or debit card), a bank account, a source, a
token, or a connected account. For certain sources—namely, cards, bank
accounts, and attached sources—you must also pass the ID of the
associated customer.
I found the solution:
if (token) {
const card = await stripe.customers.createSource(customerId, {
source: token
})
paymentInfo.source = card.id
}

PDS2 Stripe Success Webhook and other issues

This is in danger of being TLDR - so my question is: On successful payment - stripes sends a "success" payload to my success webhook. Looking through the payload, I am unable to see anything which I can use to find which payment was successful. Should I be saving something from my stripe session to my pending payment?
Greater detail:
To comply with PSD2, I've had to rejig our stripe payments. We support a few different payment options, which has affected how I go about the process.
Before, with stripe, we'd get a token - send it client side... payment made - order saved to DB.. job done.
Now, the flow is reversed...
I have a "Stripe" button - customer clicks on it. A POST is made to the server. On the server I grab the customers cart and create an order with a payment status of pending.
I then create a stripe session - and return the stripe session ID to the client (code is abridged)
//creates order and returns Order ID
const orderid = await createOrder(cart);
const stripeSession = await stripe.checkout.sessions.create({
customer_email: request.payload.billingEmail,
payment_method_types: ["card"],
line_items: [
{
name: "###",
description: "###" + orderid,
amount: cart.total.total,
currency: cart.total.currency,
quantity: 1
}
],
success_url: "###" + orderid,
cancel_url: "###/checkout"
});
return {
stripeSessionID: stripeSession.id
};
and on my client I have this method method to post to the server and automatically redirect to external stripe checkout page:
stripeCheckout: function () {
...
axios.post('/pay/get-stripe-session', data)
.then(function (response) {
var checkoutSessionID = response.data.stripeSessionID
stripe.redirectToCheckout({
sessionId: checkoutSessionID
}) ...
Upon succesful payment, stripe sends a "success" payload to my success webhook. I check the stripe signature - and receive the message... this all works... however, I can't see any data in the payload that I can use to match the payment with the order (in order to update the orders payment status).
When I create my stripe session is there anything from it that I can use?
** Edit ** -
When creating a stripe session, one can pass client_reference_id. into the create session method as a unique key. However, stripes success webhook does NOT return this key in its payload - so this cannot be used to reconcile a successful payment with an order.
We have our own customer accounts system. Under the old API we could set up a charge thus:
const charge = await stripe.charges.create({
amount: total,
currency: currency,
source: token, // obtained with Stripe.js
description: orderid
})
And the description would appear in stripes dashboard making it easy to find a payment (to make a refund or whatever). We don't use Stripes 'customers'. We store orders, and customers in our system (stripe is not a customer management system). If the customer is logged in when they check out, we link them to their order. Guest orders aren't linked to anyone.
However, under the new api where you have to create a stripeSession every session creates a customer in stripes dashboard. Can we prevent this?
Also, there is no way to add a description to the overall session / charge like you could with the old charge api - so in Stripes Payments dashboard, we end up with unusable junk for each payment description...
Does anyone know how to fix this? I hope stripe aren't having to sacrifice their wonderful developer experince to comply with PDS2
When you create the CheckoutSession, you can pass it a client_reference_id. That value will be present on the object later for you to reference an order in your own systems.
Solved it:
The trick is to set meta-data on your stripe session:
const stripeSession = await stripe.checkout.sessions.create({
customer_email: billingEmail,
client_reference_id: orderid,
payment_method_types: ["card"],
line_items: [
{
name: "My charge",
description: "Lorem ipsum",
amount: total,
currency: currency,
quantity: 1
}
],
payment_intent_data: {
description: `orderID: ${orderid}`,
metadata: {
orderid : orderid
}
},
success_url: "https://example.com/thankyou/",
cancel_url: "https://example.com/checkout"
});
The metadata is returned in the charge.success event (webhook). Using this metadata, I am able to find the order in my database and update it. In our case, I take the transaction.id, card type and last 4 card digits from the charge.success event and update the payment status to paid.
If you don't need this information - you could simply set your webhook to receive the checkout.session.complete event as that contains the client_reference_id (and I believe is stripes preferred event to confirm a transaction)
Because we're not using Customers accounts inside Stripe, I also remove the customer from stripe:
// Delete the customer from Stripes Dashboard (we don't use it - its clutter)
const customerID = event.data.object.customer
stripe.customers.del(
customerID,
function(err, confirmation) {
// asynchronously called
}
);
And thats basically it. Use the meta - it seems to be sent on every event.

Resources