How do i update a user's subscription date using stripe webhooks? - node.js

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

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).

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

Collect an email address with Stripe

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.

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.

Inconsistent - "The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console."

So here's the thing - I have a node.js backend server for my Android App. I am using the Google Play billing library, and using the backend to verify the purchase as google Docs recommend.
Now, all the other answers out there regarding this error seem to refer to a consistent problem.
My backend SOMETIMES verifies, and SOMETIMES comes back with this as an error, indicating that in fact, my service account IS linked (as shows up in my consoles).
I tried two different 3rd party libraries, and I have the same issue. Sometimes one will respond with verification success, while the other will say my account is not linked. Sometimes they are both negative, sometimes both positive.
It seems inconsistent.
var platform = 'google';
var payment = {
receipt: purchaseToken, // always required ... this is google play purchaseToken
productId: subID, // my subscription sku id
packageName: 'com.xxxxxx', // my package name
keyObject: key, // my JSON file
subscription: true, // optional, if google play subscription
};
var promise2 = iap.verifyPayment(platform, payment, function (error, response) {
/* your code */
if (error) {
console.log('error with iap, ' , error);
return true;
} else {
console.log('success with iap, response is: ', response);
return true;
}
});
I also tried with a different library, got same results:
var receipt = {
packageName: "com.xxxx",
productId: subID, // sku subscription id
purchaseToken: purchaseToken // my purchase token
};
var promise = verifier.verifySub(receipt, function cb(err, response) {
if (err) {
console.log('within err, was there a response? : ', response);
console.log('there was an error validating the subscription: ', err);
//console.log(err);
return true;
} else {
console.log('sucessfully validated the subscription');
// More Subscription info available in “response”
console.log('response is: ', response );
return true;
}
});
// return promises later.
Any else experience this issue?
TLDR; Create a new product ID.
I eventually found the answer. The problem was not with my code, or with permissions in the Google Developer Console OR the Google Play Console. Everything was set up correctly except for one thing.
Previously, before setting up Test License Accounts in Google Play Console, I had made an actual Subscription purchase with real money on my productID "X".
Then, after adding the same google account that bought the subscription as a test user, I continued to test results on the same subscription, productID "X".
Even though I had cancelled the REAL purchase, the actual expiration date was not for another month.
Therefore, I believe sometimes Google was getting confused when I would buy/cancel the purchase - confusing the test subscription with the real subscription.
Creating a new Product ID, and only using that, solved my problem, and purchases are verified consistently.

Resources