I use Setup Intents API that lets you save a customer's card without an initial payment. In addition to the payment details I want to process and see in the stripe dashboard here other information like email.
But this:
stripe
.confirmCardSetup(setupIntent.client_secret, {
payment_method: {
card: card,
billing_details: { email: email }
}
doesn't work. I can't see email in post req.
Thank you for your help
In the example below I attach the reduced code, where I try to attach to customer EMAIL. If you need to see the full logic, the code is taken from this sample: https://github.com/stripe-samples/saving-card-without-payment
var stripeElements = function(publicKey, setupIntent) {
var stripe = Stripe(publicKey);
var elements = stripe.elements();
// Element styles
var style = {
base: {
fontSize: "16px",
color: "#32325d",
fontFamily:
"-apple-system, BlinkMacSystemFont, Segoe UI, Roboto, sans-serif",
fontSmoothing: "antialiased",
"::placeholder": {
color: "rgba(0,0,0,0.4)"
}
}
};
var card = elements.create("card", { style: style });
card.mount("#card-element");
// Element focus ring
card.on("focus", function() {
var el = document.getElementById("card-element");
el.classList.add("focused");
});
card.on("blur", function() {
var el = document.getElementById("card-element");
el.classList.remove("focused");
});
// Handle payment submission when user clicks the pay button.
var button = document.getElementById("submit");
button.addEventListener("click", function(event) {
event.preventDefault();
changeLoadingState(true);
var email = document.getElementById("email").value;
stripe
.confirmCardSetup(setupIntent.client_secret, {
payment_method: {
card: card,
billing_details: { email: email }
}
})
.then(function(result) {
if (result.error) {
changeLoadingState(false);
var displayError = document.getElementById("card-errors");
displayError.textContent = result.error.message;
} else {
// The PaymentMethod was successfully set up
orderComplete(stripe, setupIntent.client_secret);
}
});
});
};
var getSetupIntent = function(publicKey) {
return fetch("/create-setup-intent", {
method: "post",
headers: {
"Content-Type": "application/json"
}
})
.then(function(response) {
return response.json();
})
.then(function(setupIntent) {
stripeElements(publicKey, setupIntent);
});
};
var getPublicKey = function() {
return fetch("/public-key", {
method: "get",
headers: {
"Content-Type": "application/json"
}
})
.then(function(response) {
return response.json();
})
.then(function(response) {
getSetupIntent(response.publicKey);
});
};
// Show a spinner on payment submission
var changeLoadingState = function(isLoading) {
if (isLoading) {
document.querySelector("button").disabled = true;
document.querySelector("#spinner").classList.remove("hidden");
document.querySelector("#button-text").classList.add("hidden");
} else {
document.querySelector("button").disabled = false;
document.querySelector("#spinner").classList.add("hidden");
document.querySelector("#button-text").classList.remove("hidden");
}
};
/* Shows a success / error message when the payment is complete */
var orderComplete = function(stripe, clientSecret) {
stripe.retrieveSetupIntent(clientSecret).then(function(result) {
var setupIntent = result.setupIntent;
var setupIntentJson = JSON.stringify(setupIntent, null, 2);
document.querySelector(".sr-payment-form").classList.add("hidden");
document.querySelector(".sr-result").classList.remove("hidden");
document.querySelector("pre").textContent = setupIntentJson;
setTimeout(function() {
document.querySelector(".sr-result").classList.add("expand");
}, 200);
changeLoadingState(false);
});
};
getPublicKey();
const express = require("express");
const app = express();
const { resolve } = require("path");
// Copy the .env.example in the root into a .env file in this folder
const env = require("dotenv").config({ path: "./.env" });
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY, {
apiVersion: '2020-08-27',
appInfo: { // For sample support and debugging, not required for production:
name: "stripe-samples/saving-card-without-payment",
version: "0.0.1",
url: "https://github.com/stripe-samples/saving-card-without-payment"
}
});
try {
app.use(express.static(process.env.STATIC_DIR));
} catch (e) {
console.log("Missing env file, be sure to copy .env.example to .env");
}
app.use(
express.json({
// We need the raw body to verify webhook signatures.
// Let's compute it only when hitting the Stripe webhook endpoint.
verify: function(req, res, buf) {
if (req.originalUrl.startsWith("/webhook")) {
req.rawBody = buf.toString();
}
}
})
);
app.get("/", (req, res) => {
const path = resolve(process.env.STATIC_DIR + "/index.html");
res.sendFile(path);
});
app.get("/public-key", (req, res) => {
res.send({ publicKey: process.env.STRIPE_PUBLISHABLE_KEY });
});
app.post("/create-setup-intent", async (req, res) => {
// Create or use an existing Customer to associate with the SetupIntent.
// The PaymentMethod will be stored to this Customer for later use.
const customer = await stripe.customers.create();
res.send(await stripe.setupIntents.create({
customer: customer.id
}));
});
// Webhook handler for asynchronous events.
app.post("/webhook", async (req, res) => {
let data;
let eventType;
// Check if webhook signing is configured.
if (process.env.STRIPE_WEBHOOK_SECRET) {
// Retrieve the event by verifying the signature using the raw body and secret.
let event;
let signature = req.headers["stripe-signature"];
try {
event = await stripe.webhooks.constructEvent(
req.rawBody,
signature,
process.env.STRIPE_WEBHOOK_SECRET
);
} catch (err) {
console.log(`⚠️ Webhook signature verification failed.`);
return res.sendStatus(400);
}
// Extract the object from the event.
data = event.data;
eventType = event.type;
} else {
// Webhook signing is recommended, but if the secret is not configured in `config.js`,
// retrieve the event data directly from the request body.
data = req.body.data;
eventType = req.body.type;
}
if (eventType === "setup_intent.created") {
console.log(`🔔 A new SetupIntent is created. ${data.object.id}`);
}
if (eventType === "setup_intent.setup_failed") {
console.log(`🔔 A SetupIntent has failed to set up a PaymentMethod.`);
}
if (eventType === "setup_intent.succeeded") {
console.log(
`🔔 A SetupIntent has successfully set up a PaymentMethod for future use.`
);
}
if (eventType === "payment_method.attached") {
console.log(
`🔔 A PaymentMethod ${data.object.id} has successfully been saved to a Customer ${data.object.customer}.`
);
// At this point, associate the ID of the Customer object with your
// own internal representation of a customer, if you have one.
// Optional: update the Customer billing information with billing details from the PaymentMethod
const customer = await stripe.customers.update(
data.object.customer,
{email: data.object.billing_details.email},
() => {
console.log(
`🔔 Customer successfully updated.`
);
}
);
}
res.sendStatus(200);
});
app.listen(4242, () => console.log(`Node server listening on port ${4242}!`));
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Saving a Card sample</title>
<meta name="description" content="A demo of Stripe Payment Intents" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="css/normalize.css" />
<link rel="stylesheet" href="css/global.css" />
<script src="https://js.stripe.com/v3/"></script>
<script src="/script.js" defer></script>
</head>
<body>
<div class="sr-root">
<div class="sr-main">
<div class="sr-payment-form card">
<div class="sr-form-row">
<label>
Account details
</label>
<input type="text" id="email" placeholder="Email address" />
</div>
<div class="sr-form-row">
<label>
Payment details
</label>
<div class="sr-input sr-element sr-card-element" id="card-element">
<!-- A Stripe card Element will be inserted here. -->
</div>
</div>
<div class="sr-field-error" id="card-errors" role="alert"></div>
<button id="submit">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Link your card to your account</span>
</button>
</div>
<div class="sr-result hidden">
<p>Card setup completed<br /></p>
<pre>
<code></code>
</pre>
</div>
</div>
</div>
</body>
</html>
You have to use your own text input fields (and validate them) to collect the customer's email and name.
Once you have that, you pass it along under the billing_details
hash like you already are passing email:
stripe
.confirmCardSetup(setupIntent.client_secret, {
payment_method: {
card: card,
billing_details: {
email: email,
name: name,
},
},
[...]
I finally figured out that I made a completely stupid mistake. I forgot to switch the running webhook from live to test key.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.