Collect an email address with Stripe - node.js

I'm following https://stripe.com/docs/payments/accept-a-payment and it works.
I need to collect a customer email address. I am using the client-server integration, as I believe this is necessary to support a dynamic price, set with the following code:
router.post("/create-payment-intent", async (req, res) => {
const stripe = require("stripe")("redacted");
const { items } = req.body;
// Create a PaymentIntent with the order amount and currency
const paymentIntent = await stripe.paymentIntents.create({
amount: calculateOrderAmount(items),
currency: "usd"
});
res.send({
clientSecret: paymentIntent.client_secret
});
});
I've been very confused by the documentation. (I've previously used PayPal for payments, which has its own issues.)
How can I collect an email address, as part of the Stripe checkout process?
Could someone point me at the correct page?

You'd collect the email address yourself, using a HTML element on your checkout page. You then have the choice to create a Stripe customer with this information and pass that into your PaymentIntent creation if you wish to reuse the customer later. Or you can just pass the email address in the receipt_email field when creating the PaymentIntent.

Related

How to update credit card payment in stripe

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

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.

How do i update a user's subscription date using stripe webhooks?

I'm building a subscription plan in node.js, I read the documentation about how to subscribe a user to a plan, and it was successful.
Stripe's doc states that I have to store an active_until field in the database. It says when something changes use webhook, i know that webhook is like an event.
The real questions are
1) how do I do a repeat the bill every month using active_until?
2) How do I use webhook, I really don't understand.
Here's the code so far.
var User = new mongoose.Schema({
email: String,
stripe: {
customerId: String,
plan: String
}
});
//payment route
router.post('/billing/:plan_name', function(req, res, next) {
var plan = req.params.plan_name;
var stripeToken = req.body.stripeToken;
console.log(stripeToken);
if (!stripeToken) {
req.flash('errors', { msg: 'Please provide a valid card.' });
return res.redirect('/awesome');
}
User.findById({ _id: req.user._id}, function(err, user) {
if (err) return next(err);
stripe.customers.create({
source: stripeToken, // obtained with Stripe.js
plan: plan,
email: user.email
}).then(function(customer) {
user.stripe.plan = customer.plan;
user.stripe.customerId = customer.id;
console.log(customer);
user.save(function(err) {
console.log("Success");
if (err) return next(err);
return next(null);
});
}).catch(function(err) {
// Deal with an error
});
return res.redirect('/');
});
});
How do i Implement the active_until timestamps and the webhook event?
active_until is just the name of a database column that you can create on your users table to store the timestamp representing when the user's account expires. The name of the column doesn't matter. You can use any name you want.
In order to verify if a user's subscription is current, Stripe is suggesting that you use logic like this:
If today's date <= user.active_until
allow them access
Else
show them an account expired message
The webhook is a request that Stripe's servers make to your server to tell you that something has happened. In this case, the event you are most interested in is invoice.payment_succeeded.
Your webhook will include logic like this:
if event type is "invoice.payment_succeeded"
then update user.active_until to be equal to today's date + 1 month
You will also want to respond to other events in case the payment fails, etc.
You don't need to repeat the bill every month. Stripe will do it for you.
Once you subscribed your user to a plan, stripe will charge him till the paid period is over.
Every time stripe charges a customer it will generate a webhook, that is a request on your server to some specified URL. Stripe can generate different webhooks for different reasons.
For example when customer gets charged by subscription, Stripe will send you info about payment.
router.post('/billing/catch_paid_invoice', function(req, res) {
// Here you parse JSON data from Stripe
}):
I don't have access to Stripe settings right now, but a remember setting urls for webhooks manually.
Select your account name > Account Settings > Webhooks
active_until is just a reminder that customer is still active and have paid services in your system. It needs to be updated when getting webhooks.
Stripe docs are really good, so go through them one more time.
https://stripe.com/docs/guides/subscriptions

Resources