Stripe Node js charge a customer - javascript

All I am trying to do is charge a customer like this:
var stripe = require("stripe")("sk_test_5uwvjas5uFYUCZN5d3YdAT19");
stripe.charges.create({
amount: 1000,
currency: "usd",
customer: "cus_112121212", // CUSTOMER ID
destination: {
account: "{CONNECTED_STRIPE_ACCOUNT_ID}",
},
}).then(function(charge) {
// asynchronously called
});
According to the documentation:
https://stripe.com/docs/api/charges/create
This should be possible,
Yet i get the error:
there was an issue Error: No such token: cus_111212122112
Am I reading the docs wrong? Thank you.

Review Firestripe example since it’s in Node js.
https://github.com/firebase/functions-samples/blob/master/stripe/functions/index.js
If that doesn’t help, confirm that customer have a source attached to it. If not, then you can’t charge that customer.

Related

Card payments with the Payment Request API not working

I am looking into the Payment Request API as a way to streamline payments on our site checkout and have run into a bit of a brick wall on how to use it with card payments. There are a few demos explaining how to use the payment request API, this one seemed to be the simplest and easiest to follow, but it is also quite out of date (as a lot of PR API demos i've found seem to be). Here is my code than runs when the payment button is clicked:
const paymentMethods = [
{
supportedMethods: ['basic-card', 'visa', 'mastercard', 'amex'],
data: {
supportedNetworks: ['visa', 'mastercard', 'amex']
}
}
];
const details = { total: { label: 'Test payment', amount: { currency: 'GBP', value: '1.00' } } };
// Show a native Payment Request UI and handle the result
const request = new PaymentRequest(paymentMethods, details);
request.show()
.then(response => {
console.log('yep');
console.log(response);
})
.catch(err => {
console.error(err);
});
I get the following error in the console:
Uncaught RangeError: Failed to construct 'PaymentRequest': Invalid payment method identifier format
I did some digging and found that the 'basic-card' supportedMethod is deprecated, and simple references to credit card providers don't seem to be supported anymore. The MDN docs for supportedMethods actually state
Starting with more recent browsers, this parameter is more generic than credit cards, it is a single string, and the meaning of the data parameter changes with the supportedMethods. For example, the Example Pay payment method is selected by specifying the string https://example.com/pay here.
Which is all well and good, but if i want to support Visa or Mastercard credit and debit card payments what URL do i use for them under supported methods? The payment processor for our website is Worldpay, so is this something i'd ask them for? Or do i need to find individual urls for Visa and Mastercard? I have done some googling and can't find anything relevant for either of them. Maybe i'm just bad at googling, but i don't really know how to proceed with this and wondered if anyone else had experience in setting up the payment request API to use credit and debit cards.
Oh, and i'm testing this in Chrome 103 btw.
Thanks

Using confirmSetupIntent on stripe-react-native

I'm making a shift from tipsi-stripe to stripe-react-native and I'm having some trouble getting confirmSetupIntent to work.
I'm getting a paymentIntentClientSecret from our server, and I have a custom credit card form from which I used to collect the card details and send in to confirmSetupIntent on tipsi-stripe, but it seems like that this doesn't work on stripe-react-native.
I'm calling the function like so, with some placeholder test data:
const result = await confirmSetupIntent(
clientSecret,
{
type: 'Card',
},
{
brand: 'Visa',
last4: '4242',
expiryYear: 22,
expiryMonth: 4,
postalCode: '90001',
}
)
console.log('Stripe confirmSetupIntent result', result)
And I get the following response:
I guess I'm not sure how Stripe expects the card details to be passed in. Has anyone else experienced the same issue? Any help is greatly appreciated!
Found the solution. It seems like we can only use the components provided by Stripe due to PCI DSS requirements. That's why this error occurs. Read more here.

How can I provide billing details for SCA compliance using Stripe Payment Intents?

I am using Stripe Payment Intents, following the instructions in the Payment Intents Quickstart. As the docs note:
To ensure that your integration is SCA-ready, be sure to always provide the customer’s name, email, billing address, and shipping address (if available) to the stripe.handleCardPayment call.
const stripe = Stripe('pk_test_lolnothisisnotreal', {
betas: ['payment_intent_beta_3']
})
Per the handleCardPayment doc in the link, I am providing billing details in the format specified:
// https://stripe.com/docs/stripe-js/reference#stripe-handle-card-payment
const {paymentIntent, error} = await stripe.handleCardPayment(clientSecret, cardElement, {
// https://stripe.com/docs/api/payment_methods/create#create_payment_method-billing_details
payment_method_data: {
billing_details: {
address: {
line1: cardholderAddressLine1.value,
line2: cardholderAddressLine2.value,
city: cardholderAddressCity.value,
state: cardholderAddressState.value,
country: cardholderAddressCountry.value,
postal_code: cardholderAddressPostalCode
},
name: cardholderName.value,
email: cardholderEmail.value,
phone: cardholderPhone.value
}
}
})
However handleCardPayment() returns:
Received unknown parameter: source_data[billing_details]
How can I provide billing details for SCA compliance using Stripe Payment Intents?
The code is passing payment_method_data[billing_details] which is how you provide details such as the cardholder's billing address to associate it with the PaymentMethod resource that is created.
The issue though is that this only works if you have not initialized Stripe.js with an old beta flag where handleCardPayment would create a Source object (src_123) behind the scenes instead of a PaymentMethod (pm_123).
When you do that, the library will translate payment_method_data to source_data and then cause source_data[billing_details] to be sent, but the API server-side rejects it since it's not a valid parameter server-side.
To avoid this error, you need to ensure that you initialize Stripe.js without the betas flag. So turn
const stripe = Stripe('pk_test_123', { betas: ['payment_intent_beta_3'] });
into:
const stripe = Stripe('pk_test_123');

How to disable default payment method (Credit Card) in Stripe Checkout

I need only one Payment Method (AliPay). But I can't disable default payment method with Stripe Checkout (Credit Card). Of course, I read documentation, but I don't have any idea how I can make that.
This is My code.
var handler = StripeCheckout.configure({
key: 'public_key',
alipay: true,
locale: false,
currency: "usd",
token: function(token) {
// Use the token to create the charge with a server-side script.
// You can access the token ID with `token.id`
}
});
handler.open({
name: 'example.com',
description: 'AliPay Payment',
amount: 10000
});
Thanks!
It's not possible to disable the default (card) area of Checkout.
If you're looking for greater customizability of your payment form I'd have a look at Stripe.js/Elements and the Sources API. You can use the Sources
to generate an AliPay source, redirect a user to AliPay to authorize a payment, and then return them to your site, https://stripe.com/docs/sources/alipay

Need guidance trying to setup a variable amount with stripe using node js

I'm new to node and javascript so please excuse me. This is what I have right now, just copied it from the Stripe docs. I'm confused as to what I'm supposed to do with the commented token function. I was using the simple Stripe configuration and got everything working perfectly but I decided that I want to allow a custom amount to be set by the user via an input field. Any help to guide me in that direction would be awesome.
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Purchase</button>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_...',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Demo Site',
description: '2 widgets',
amount: 2000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
And here's my server-side code (stripe.js):
var express = require('express');
var router = express.Router();
var stripe = require('stripe')('sk_test_...');
router.post('/charge', function(req, res, next) {
var token = req.body.stripeToken;
var chargeAmount = req.body.chargeAmount;
var charge = stripe.charges.create({
amount: 2000,
currency: "usd",
source: token
}, function(err, charge) {
if(err) {
return console.log(err);
}
console.log(req.body);
res.redirect('/users/dashboard');
});
});
module.exports = router;
Checkout does not send the amount and currency to the backend server -- it only uses the amount and currency parameters for display purposes.
This is by design. Outside of scenarios where the amount should explicitly be set by the paying customer (e.g. if you're accepting donations), you cannot trust an amount that is sent by the customer's browser as it would be very easy to modify it.
But in this case, it sounds like you do want the amount to be set by the customer. So you need to do this:
In your client-side (frontend) code, make sure that the amount is sent along with the token returned by Checkout.
Here is a simple example of a form where the amount is set by the customer: https://jsfiddle.net/ywain/g2ufa8xr/. In this form, the amount will be sent as the amount POST parameter, along with the stripeToken and stripeEmail parameters returned by Checkout.
In your server-side (backend) code, use the amount in the charge creation request.
This is easy, simply retrieve the parameter and use it as the value of the amount parameter of the charge creation request:
var token = req.body.stripeToken;
var amount = req.body.amount;
var charge = stripe.charges.create({
amount: amount,
currency: "usd",
source: token
}, function(err, charge) {
...
}
As a side note, please never share your secret API key publicly, even if it's just a test key. You should roll out a new key ASAP. You can do this by heading to your dashboard: https://dashboard.stripe.com/account/apikeys and clicking the "recycle" icon next to the key you want to replace.

Categories