Fliplet.Payments
Fliplet.Payments takes Stripe payments in your project. Fliplet creates the Stripe Checkout Session on its servers with your project’s own Stripe keys, opens Stripe’s hosted checkout page and can record each payment on a data source row from Stripe’s webhook, so your project’s code never holds a Stripe secret key.
Dependency name: fliplet-payments
- What you can build
- How it works
- Before you start
- Quick start: a one-off checkout
- Handling the result
- Recording payments on a data source row
- Test mode and going live
- Worked examples
- API reference
- Troubleshooting
What you can build
Every scenario below uses the same call, Fliplet.Payments.Checkout.create(). Fliplet passes your options to Stripe’s Checkout Session create API, so anything Stripe’s hosted checkout supports works here. Call it from a click handler, as in the quick start.
A price your project works out
Such as a cart or a booking. Recorded on a row: yes. Fliplet checks the currency and a minimum amount, not each order’s exact total.
Fliplet.Payments.Checkout.create({
mode: 'payment',
line_items: [{
quantity: 2,
price_data: {
currency: 'usd',
unit_amount: 30500, // smallest currency unit: 30500 = $305.00
product_data: { name: 'Full conference ticket' }
}
}]
});
Product catalog
Products priced in Stripe, listed in a products data source. Recorded on a row: yes. Price IDs are different in test and live mode.
// product is a row from Fliplet.Payments.Products.get()
Fliplet.Payments.Checkout.create({
mode: 'payment',
line_items: [{ price: product['Price ID'], quantity: 1 }]
});
Subscription or membership
Recorded on a row: the first payment only. Renewals and cancellations reach you as Stripe events through Customers.getLogs(). See the membership example.
// customer: from Customers.create() for the signed-in member
Fliplet.Payments.Checkout.create({
mode: 'subscription',
customer: customer.id,
line_items: [{
quantity: 1,
price_data: {
currency: 'usd',
unit_amount: 1500, // $15.00 a month
recurring: { interval: 'month' },
product_data: { name: 'Monthly membership' }
}
}]
});
Free trial on a subscription
Recorded on a row: no. The trial’s first payment is zero, and a zero total is never recorded. Follow the subscription through Customers.getLogs().
Fliplet.Payments.Checkout.create({
mode: 'subscription',
customer: customer.id,
// A recurring Price from your Stripe Dashboard
line_items: [{ price: 'price_1Q2w3E4r5T6y7U8i', quantity: 1 }],
subscription_data: { trial_period_days: 14 }
});
Donation or pay what you want
Recorded on a row: yes, when the amount clears minimumAmountTotal. Convert the buyer’s amount to the smallest currency unit.
// The amount the buyer typed, in dollars, such as 25
var amount = Number(document.querySelector('#donation-amount').value);
if (amount > 0) {
Fliplet.Payments.Checkout.create({
mode: 'payment',
submit_type: 'donate', // Stripe's button reads "Donate"
line_items: [{
quantity: 1,
price_data: {
currency: 'usd',
unit_amount: Math.round(amount * 100), // $25 becomes 2500
product_data: { name: 'Donation' }
}
}]
});
}
Promo codes and tax
Recorded on a row: yes. The minimum amount is checked after discounts. A 100% code completes checkout with a zero total, which is never recorded, so don’t offer 100% codes on orders you record. Set up promo codes and Stripe Tax in your Stripe Dashboard first, in each mode.
Fliplet.Payments.Checkout.create({
mode: 'payment',
line_items: lineItems,
allow_promotion_codes: true, // the buyer types a code on Stripe's page
automatic_tax: { enabled: true } // Stripe works out the tax
});
An invoice for a paid order
Recorded on a row: yes. Stripe creates an invoice after the payment, and emails it when invoice emails are turned on in your Stripe settings.
Fliplet.Payments.Checkout.create({
mode: 'payment',
line_items: lineItems,
customer_email: buyerEmail,
invoice_creation: { enabled: true }
});
Deposit, then the balance
Recorded on a row: yes, per row. Run one checkout for each payment, each with its own order row.
Save a card for later
mode: 'setup' saves a card in Stripe. Recorded on a row: no. There is no API to charge the saved card later.
What isn’t supported
Fliplet.Payments does not support these, so don’t build around them:
- Stripe’s embedded or custom checkout (
ui_mode). Only the hosted checkout page works. - Your own
success_urlorcancel_url. Fliplet sets both and brings the buyer back through the checkout window. - Refunds from the project. Refund in the Stripe Dashboard. Fliplet does not change the row back.
- Sending a Stripe invoice that the customer pays later. To collect later, save the order unpaid and send the buyer a link to a screen that opens checkout for that row. The link must carry the order’s ID and its secret reference, and the screen sends them as
client_reference_idandflPurchaseToken. A guest can’t read orders, so the screen can’t look the reference up, and without it checkout is refused with a403. - Charging a saved card later, without the buyer present.
- App Store or Google Play in-app purchases.
How it works
- Your screen calls
Fliplet.Payments.Checkout.create()from a button click. - Fliplet’s server creates the Checkout Session in Stripe with your project’s secret key.
- Stripe’s hosted checkout opens in a new window (an in-app browser on mobile). The buyer pays there.
- The window closes and the promise settles. Fliplet asks Stripe how the checkout ended, so the result does not depend on the window reporting back.
- Stripe calls Fliplet’s webhook. If you set up payment recording, Fliplet marks the order row paid, even when the buyer’s browser has closed.
Open checkout straight from the click. Browsers only open a window for a short time after a click, and Checkout.create() already makes two quick server calls before it opens one. Do slower work, such as loading products or saving the order, before the buyer clicks Pay, so the click handler only calls Checkout.create().
What Fliplet sends to Stripe. Everything you pass to Checkout.create() goes to Stripe as you sent it, with three exceptions. Fliplet sets success_url and cancel_url itself, removes flPurchaseToken, and replaces the flFulfilment and flOrigin keys in metadata.
Stripe API version. Fliplet sends no Stripe-Version header, so every request uses the default API version of the Stripe account that owns the keys. You can see it in Stripe’s Workbench. That version decides which options Stripe accepts. When Stripe rejects an option, its error message comes back as the Checkout.create() rejection. Webhook events use the API version set on the webhook endpoint. See Stripe API versions.
One set of keys per project. The keys are saved once for the project you edit in Studio. Studio preview and the published project use the same keys.
Stripe references you will need:
- Checkout Session create: every option
Checkout.create()accepts - The Checkout Session object: what Stripe returns and sends in webhooks
- Event types: the webhook events you can subscribe to
- Testing: test cards and failure scenarios
Before you start
You need a Stripe account. Use test mode until checkout works end to end.
In a V3 project, the AI builder’s Stripe setup form does steps 2 and 3 for you: it saves the keys and the optional products data source, shows the webhook URL and saves the signing secret. You only add the endpoint in Stripe.
1. Add the dependency
Add fliplet-payments to your project or screen dependencies.
2. Save your Stripe keys
Save the keys with Fliplet.Payments.Configuration.update(), signed in to Studio as a user of the project’s organization. The keys are stored in the organization’s credentials for this project, never in the project’s settings or code. Checkout works as soon as the keys are saved.
Run this from the browser console or a one-off script while signed in to Studio. Never put it in a screen: anyone using the project could read your secret key.
// Run once, signed in to Studio.
// Get the keys from https://dashboard.stripe.com/apikeys (test mode first).
Fliplet.Payments.Configuration.update({
provider: 'stripe',
providerPublicKey: 'pk_test_51Hx...', // Publishable key
providerPrivateKey: 'sk_test_51Hx...', // Secret key
productsDataSourceId: 123 // Optional: only if you sell from a products data source
}).then(function (result) {
// Add this URL as a webhook endpoint in Stripe, see the next step.
// It looks like https://api.fliplet.com/v1/billing/webhook/apps/8a85a2edc3f3a774ac06f
console.log('Webhook URL:', result.webhookUrl);
});
Calling it again updates the fields you pass. Fields you leave out, such as productsDataSourceId, keep their saved values.
3. Add the webhook in Stripe
The webhook is what lets Fliplet record payments on a row and store events for Customers.getLogs().
- In Stripe, go to Developers > Webhooks and click Add endpoint.
- Paste the
webhookUrlfrom the previous step into Endpoint URL. -
Select the events you need:
Events Needed for checkout.session.completedandcheckout.session.async_payment_succeededRecording payments on a row. async_payment_succeededis the settlement of a delayed payment method, which can arrive minutes or days latercustomer.subscription.created,customer.subscription.updatedandcustomer.subscription.deletedFollowing subscriptions through Customers.getLogs()Every event Stripe sends is also stored for
Customers.getLogs(). An endpoint with only the subscription events never records a one-off payment.
-
Save the endpoint and copy its Signing secret:

-
Save the signing secret, signed in to Studio:
// Run once, signed in to Studio. Fliplet.Payments.Configuration.updateSigningSecret('whsec_...').then(function () { // Stripe's webhook deliveries can now be verified. });
Fliplet does not act on checkout.session.async_payment_failed. When a delayed payment method such as SEPA Direct Debit fails, the row stays unpaid. A payment that settles and is later disputed or refunded is not changed back.
Quick start: a one-off checkout
This is the smallest checkout that works: a buyer pays $25.00 for one workshop ticket. It needs no products data source and no sign-in.
The buyer’s browser sends the amount, so treat it as what the buyer asked to pay, not as proof of payment. This example records nothing. Never mark an order paid from the page: set up payment recording so Fliplet’s webhook does it.
document.querySelector('#buy-ticket').addEventListener('click', function () {
var buyerEmail = document.querySelector('#email').value.trim();
Fliplet.Payments.Checkout.create({
mode: 'payment',
line_items: [{
quantity: 1,
price_data: {
currency: 'usd',
unit_amount: 2500, // smallest currency unit: 2500 = $25.00
product_data: { name: 'Workshop ticket' }
}
}],
// Optional. Stripe pre-fills it and sends its receipt there.
// Leave it out rather than sending an empty string, which Stripe rejects.
customer_email: buyerEmail || undefined
}).then(function (session) {
// Checkout completed. session.id is the Stripe Checkout Session ID.
showConfirmation(session.id);
}).catch(handleCheckoutError); // defined in "Handling the result" below
});
Leave out payment_method_types. Stripe then offers the payment methods turned on in your Stripe Dashboard.
Handling the result
When the promise resolves, the checkout completed. That is not always money in your account:
- A delayed payment method (bank debit, Klarna) completes before the money arrives.
- A zero-total checkout, such as a 100% promo code or a free trial, completes without a payment.
mode: 'setup'completes without a payment.
It resolves with the session as it was when checkout started: id, currency, customer, customer_details and customer_email. It does not include amount_total or payment_status, and customer_details is usually null. Show the confirmation from the order your page already holds.
When the promise rejects, the reason tells you what happened. T() is Fliplet’s translation function, available in every project. The rejection is the translated text, so compare against T(...), not the key:
function handleCheckoutError(error) {
if (error === T('app.payments.error.paymentIncomplete')) {
// Stripe says the checkout ended without a payment. Nothing was charged.
// A blocked pop-up also lands here, because no Stripe page opened.
showMessage('Your payment was not completed. You can try again.');
} else if (error === T('app.payments.error.paymentPending')) {
// Fliplet stopped watching before Stripe decided. The payment may still
// succeed, and the webhook records it if it does.
showMessage('Your payment is still being confirmed. Please do not pay again.');
} else {
// Checkout did not start: Stripe rejected an option, the order was
// refused (403), or the network failed. Log the cause for debugging.
console.error('Checkout could not start:', Fliplet.parseError(error));
showMessage('Checkout could not start. Please try again.');
}
}
Treat paymentPending differently from paymentIncomplete. Telling a buyer their card was not charged while the charge is still in flight is how a second charge happens.
Recording payments on a data source row
Everything in the quick start runs in the buyer’s browser. If that browser closes, loses its connection or is put to sleep before Stripe’s confirmation arrives, the payment succeeds in Stripe while your project never finds out. Payment recording fixes this: Fliplet marks the row paid from Stripe’s webhook, whatever happens to the browser.
Recording works only for checkouts created with Fliplet.Payments.Checkout.create(). Fliplet marks each of those sessions when it creates them, and the webhook ignores any session without that mark. Sessions from Stripe Payment Links, the Stripe Dashboard or another integration are never recorded.
Limits to know before you start:
- One currency per project, set by
expectedCurrency. minimumAmountTotalis one floor for the whole project, not the price of each order. Fliplet does not compare the amount paid with the order: a buyer who changes the amount in their browser can pay the floor for a more expensive order and still have it marked paid. Set the floor to your cheapest genuine order after any discount, and compare payments with orders in the Stripe Dashboard when amounts matter.- A zero total is never recorded, and neither is
mode: 'setup'. - A subscription records its first payment only.
- Details Stripe collects, such as a shipping address or phone number, stay in Stripe. Fliplet writes only the status and the Stripe IDs to the row.
The paymentFulfilment setting
Recording is configured with the paymentFulfilment project setting:
{
"paymentFulfilment": {
"dataSourceId": 123456,
"statusColumn": "Payment Status",
"paidValue": "Paid",
"expectedCurrency": "usd",
"minimumAmountTotal": 2500,
"ownershipTokenColumn": "Order Reference",
"sessionColumn": "Stripe Session ID",
"paymentIntentColumn": "Stripe Payment Intent ID",
"customerColumn": "Stripe Customer ID",
"runUpdateHooks": false
}
}
| Key | Required | Meaning |
|---|---|---|
dataSourceId |
Yes | The orders data source. It must belong to the project you edit in Studio |
statusColumn |
Yes | The column Fliplet writes when the payment is confirmed |
paidValue |
Yes | The value written to statusColumn, such as Paid |
expectedCurrency |
Yes | Three-letter currency code. A payment in another currency is not recorded |
minimumAmountTotal |
Yes | The smallest total that counts, in the currency’s smallest unit (2500 = $25.00). Must be above 0 |
ownershipTokenColumn |
For guest buyers | A column holding a secret per-row reference. See Proving the buyer owns the row |
sessionColumn, paymentIntentColumn, customerColumn |
No | Filled with Stripe’s IDs, only where the row leaves them blank |
runUpdateHooks |
No | Runs the data source’s update hooks for the recorded payment. Off by default. See Update hooks |
Without dataSourceId, statusColumn or paidValue, Fliplet treats the project as not recording payments and logs nothing.
Your checkout must name the row with client_reference_id, as a string, and send the row’s secret reference:
// orderId and orderReference come from the order you saved before checkout
Fliplet.Payments.Checkout.create({
mode: 'payment',
line_items: lineItems,
client_reference_id: String(orderId),
flPurchaseToken: orderReference // see "Proving the buyer owns the row"
});
A paid checkout without client_reference_id is not recorded, and Fliplet logs why (see When a payment isn’t recorded).
What the data source needs
- It belongs to the project you edit in Studio, not its published copy or another project.
statusColumnand every column you name exist. If the data source has no column list, a misspelledstatusColumnis not caught: the value is written under the misspelled name and the real column stays unchanged.- Buyers may create rows but never mark them paid. Save each order with the status
Unpaid, and make the insert rulerequirethat value.excludealone doesn’t protect the status: bulkappend()keeps excluded columns, whilerequirechecks every record. Exclude the status and Stripe columns from any update rule buyers have. Fliplet’s webhook writes the paid value and the Stripe columns itself.
Security rules for an orders data source where guests buy and nobody reads orders back in the project:
[
{
"type": ["insert"],
"allow": "all",
"require": [{ "Payment Status": { "equals": "Unpaid" } }],
"exclude": ["Stripe Session ID", "Stripe Payment Intent ID", "Stripe Customer ID"]
}
]
With these rules, connection.insert() resolves with the new row’s id but not its data, because buyers can’t read orders. Keep the values you need, such as the order reference, in your own variables.
An order is paid only when its status is your paidValue.
Proving the buyer owns the row
client_reference_id arrives from the browser, and row IDs are sequential and easy to guess. Before creating the session, Fliplet checks that the buyer may pay for the row they named. Otherwise a buyer could pay against someone else’s order and have it marked paid on their behalf.
The check passes in one of two ways:
- Access rules. The buyer is signed in and the data source’s rules let them update that row.
- A per-row secret. Name a column with
ownershipTokenColumnand send its value asflPurchaseToken. Use this for guests, and also for signed-in buyers when your rules don’t grant them updates.
Generate the secret when you create the row, with crypto.getRandomValues() as in the event registration example. Avoid crypto.randomUUID(): older native-app WebViews and pages not served over HTTPS don’t have it. The secret must be at least 16 characters (16 bytes). A shorter or blank value authorizes nothing. Fliplet removes flPurchaseToken before calling Stripe, so the secret never reaches a third party.
If neither check passes, checkout is refused with a 403 and the buyer never reaches Stripe.
Saving paymentFulfilment turns on this check in Studio preview and in the published project at once, before any republish. It applies to every checkout that sends a numeric client_reference_id. If the project's screens don't send flPurchaseToken yet and its rules don't grant buyers an update, those checkouts start failing. A numeric client_reference_id that isn't a row of the orders data source is refused with a 403 too, so a project that already sends something else there, such as a member ID, breaks as soon as the setting is saved. Ship the token first, then turn on recording.
Saving the setting
Save paymentFulfilment with the REST API against the ID of the project you edit in Studio, signed in as a Studio user who can edit it. In a V3 project, the AI builder saves it for you. See Saving settings.
POST v1/apps/:masterAppId/settings
{
"paymentFulfilment": {
"dataSourceId": 123456,
"statusColumn": "Payment Status",
"paidValue": "Paid",
"expectedCurrency": "usd",
"minimumAmountTotal": 2500,
"ownershipTokenColumn": "Order Reference"
}
}
The endpoint returns a 403 for a published project’s ID, so always use the ID of the project you edit in Studio. It replaces paymentFulfilment as a whole: always send the complete object. Sending only the fields you want to change deletes the rest.
Don't use Fliplet.App.Settings.set() for this. In a published project it targets the published copy, which the endpoint refuses with a 403.
Republish after every change. Checkout reads the published project’s copy of the setting, or the Studio project’s when the project has never been published with one. The webhook always reads the Studio project’s copy. If the two name different data sources, payments are not recorded, and each one logs session carries no valid server-issued fulfilment binding.
When a project is copied, the copy has no Stripe keys: its checkout fails with “Payments have not been configured for this app” until you save keys for it. It gets its own webhook URL, so add a new endpoint in Stripe with its own signing secret, and point paymentFulfilment at the copy’s own data source.
Update hooks
With runUpdateHooks set to true, the webhook’s write runs the data source’s update hooks, such as a confirmation email.
- If your screens also write the row when the buyer returns, the same hooks run again, so an update hook with no condition sends two emails. Make each update hook fire only on the change it cares about, for example when
Payment StatusbecomesPaid, and decide whether the webhook or your screens send the confirmation. - A hook with a
triggerslist runs from the webhook only when that list includeswebhook. Leavetriggersout, or addwebhook.
Log-triggered App Actions see the webhook’s write either way, as a dataSource.entry.update on the project the checkout was opened from.
When a payment isn’t recorded
For a project with payment recording, Fliplet writes payment outcomes to the project’s audit log. These entries hold IDs and the values that failed, never buyer details.
| Log type | Meaning | data |
|---|---|---|
app.billing.recorded |
The row was marked paid. The row’s ID is in the log’s dataSourceEntryId |
sessionId, dataSourceId, statusColumn, paidValue, source |
app.billing.notRecorded |
The payment, or a webhook delivery, could not be written to a row | reason, plus sessionId, entryId and the values that failed when there is a session |
app.billing.pending |
Checkout completed but a delayed payment method hasn’t settled. Nothing to fix: it’s recorded when the money arrives | sessionId, entryId, paymentStatus, eventType |
app.billing.recordedWithout |
The row was marked paid but a follow-up step, such as log triggers, did not run | step, reason, sessionId, entryId |
Common reason values and their fixes:
session currency does not match the configured currency: changeexpectedCurrencyor the checkout’scurrency.session amount is below the configured minimum: lowerminimumAmountTotalto your cheapest genuine order after discounts. A zero total can never be recorded.checkout did not set client_reference_id, so no row was named: sendclient_reference_idwith the checkout.statusColumn is not a column of the configured data source: fix the column name.session carries no valid server-issued fulfilment binding: the checkout did not come fromCheckout.create()for this row, ordataSourceIdchanged without republishing.Stripe's webhook signature could not be verified; most often the saved signing secret belongs to another endpoint or mode: save the signing secret of this endpoint, in the same mode as your keys.the webhook signing secret has not been saved for this project: save it withConfiguration.updateSigningSecret().the Stripe keys have not been saved for this project: save them withConfiguration.update().no such entry in the configured data source: the row named byclient_reference_idwas deleted, or belongs to another data source.data source belongs to another app: pointdataSourceIdat a data source of the project you edit in Studio.fulfilment is configured without expectedCurrency and minimumAmountTotal: add both topaymentFulfilment.session mode cannot collect a payment:mode: 'setup'saves a card and is never recorded.
Fliplet logs nothing for a payment the row had already recorded, such as a Stripe redelivery.
To read these entries, query the audit log of the project you edit in Studio, signed in as one of its editors. The audit log needs a paid plan. In a V3 project, the AI builder reads it for you.
// Run signed in to Studio. masterAppId is the ID of the project you edit.
Fliplet.API.request({
url: 'v1/apps/' + masterAppId + '/logs',
method: 'POST',
data: {
where: { type: ['app.billing.notRecorded', 'app.billing.pending', 'app.billing.recorded'] },
order: [['createdAt', 'DESC']],
limit: 20
}
}).then(function (response) {
response.logs.forEach(function (log) {
console.log(log.createdAt, log.type, log.data.reason || '');
});
});
Every verified delivery from Stripe also writes an app.billing entry, which holds the event’s data: the Stripe object, buyer details included. No app.billing entry for a payment means Stripe never delivered it or Fliplet rejected the delivery: look for an app.billing.notRecorded entry about the signing secret or keys, then check the endpoint’s events and delivery attempts in Stripe.
Test mode and going live
The same code runs in test and live mode, because your keys never appear in it. Going live changes the saved keys, the webhook endpoint and, for a catalog, the Price IDs. Never write a second version of your checkout code for live mode.
Testing. With test keys, pay with Stripe’s test card 4242 4242 4242 4242, any future expiry date and any CVC. No money moves. See Testing for declines and other scenarios.
Studio preview and the published project share one set of keys. Once live keys are saved, a checkout in Studio preview charges a real card.
Going live. In a V3 project, the AI builder runs its Stripe setup form again with your live values. Otherwise:
- Save your live keys with
Configuration.update(). This replaces the test keys. - In Stripe’s live mode, add a webhook endpoint with the same Fliplet URL and the same events. Live mode has its own endpoints.
- Save the live endpoint’s signing secret with
Configuration.updateSigningSecret(). Until you do, live deliveries fail and Stripe retries them, so payments made in between are recorded once the secret is saved, as long as Stripe is still retrying. - For a catalog, update the products data source with the live Price IDs. Test and live Price IDs are different values for the same product.
- Turn off the test-mode endpoint in Stripe (Developers > Webhooks, in test mode, then the endpoint > Disable). It points at the same Fliplet URL, so once the live signing secret is saved its deliveries fail and show up as signature errors in the audit log.
- Repeat in live mode any Stripe setup you made in test mode, such as Prices, promo codes, Stripe Tax and billing portal settings.
paymentFulfilment doesn’t change.
Worked examples
An event registration
Goal: guests register for an event, the project works out the price, and each paid order is marked Paid even if the buyer closes the browser.
Prerequisites: keys and a webhook with the checkout events (Before you start), and the fliplet-payments dependency on the registration screen.
Steps:
-
Create an
Ordersdata source with these columns:Order Reference,Attendee Name,Email,Ticket,Total Cents,Payment StatusandStripe Session ID.Expected result: the columns appear in the data source.
-
Set its security rules so guests can create unpaid orders but can’t mark them paid:
[ { "type": ["insert"], "allow": "all", "require": [{ "Payment Status": { "equals": "Unpaid" } }], "exclude": ["Stripe Session ID"] } ]Expected result: an insert with
Payment Statusset to anything butUnpaid, including throughappend(), is refused. -
Save the setting against the project you edit in Studio, then republish:
{ "paymentFulfilment": { "dataSourceId": 123456, "statusColumn": "Payment Status", "paidValue": "Paid", "expectedCurrency": "usd", "minimumAmountTotal": 8000, "ownershipTokenColumn": "Order Reference", "sessionColumn": "Stripe Session ID" } }minimumAmountTotalis the cheapest ticket, $80.00. A $305.00 order paid at $80.00 would still be markedPaid, so compare payments with orders in the Stripe Dashboard if that matters. -
Use one pricing function to show the price and to charge it:
// Prices in cents. One function for display and checkout, // so what the buyer sees is what Stripe charges. var PRICES = { full: 30500, singleDay: 24500, workshop: 8000 }; function priceFor(ticket) { return PRICES[ticket]; } -
Save the order when the buyer confirms their details, before showing the Pay button:
var pendingOrder = null; // { id, reference, ticket, email } // 16 random bytes as 32 hex characters. crypto.getRandomValues works in // every WebView; crypto.randomUUID is missing on older ones. function newReference() { return Array.from(crypto.getRandomValues(new Uint8Array(16)), function (byte) { return ('0' + byte.toString(16)).slice(-2); }).join(''); } document.querySelector('#review').addEventListener('click', function () { var ticket = document.querySelector('#ticket').value; // 'full', 'singleDay' or 'workshop' var email = document.querySelector('#email').value.trim(); var reference = newReference(); // the buyer's secret // offline: false, so the order is saved on the server before Pay is // enabled. A queued offline insert has a temporary id that checkout // can't record a payment against. Fliplet.DataSources.connectByName('Orders', { offline: false }).then(function (orders) { return orders.insert({ 'Order Reference': reference, 'Attendee Name': document.querySelector('#name').value, 'Email': email, 'Ticket': ticket, 'Total Cents': priceFor(ticket), 'Payment Status': 'Unpaid' // the insert rule requires it }, { offline: false }); }).then(function (row) { // Buyers can't read orders, so the reply has the row's id but not its data. pendingOrder = { id: row.id, reference: reference, ticket: ticket, email: email }; document.querySelector('#pay').disabled = false; }).catch(function (error) { console.error('Could not save the order:', Fliplet.parseError(error)); showMessage('We couldn\'t save your order. Check your connection and try again.'); }); });Expected result: a row appears in
OrderswithPayment Statusset toUnpaid. -
Start checkout from the Pay button, with nothing slow before it:
document.querySelector('#pay').addEventListener('click', function () { if (!pendingOrder) { return; } Fliplet.Payments.Checkout.create({ mode: 'payment', line_items: [{ quantity: 1, price_data: { currency: 'usd', unit_amount: priceFor(pendingOrder.ticket), product_data: { name: 'Spring Conference: ' + pendingOrder.ticket } } }], customer_email: pendingOrder.email || undefined, client_reference_id: String(pendingOrder.id), flPurchaseToken: pendingOrder.reference }).then(function () { // Show the confirmation from what the page holds. The webhook marks // the row paid, usually within seconds. showConfirmation(pendingOrder.ticket, priceFor(pendingOrder.ticket)); }).catch(handleCheckoutError); });Expected result: Stripe’s checkout opens, and after paying the confirmation shows.
-
Pay with the test card
4242 4242 4242 4242.
Verification:
- In Studio, the order row shows
Payment StatusasPaidand aStripe Session ID. - The project’s audit log has an
app.billing.recordedentry for the session. - Guests can only be tested on the published project: Studio preview always carries your Studio sign-in. Publish, then pay again in a private browser window and check that row too.
Common pitfalls:
- The row stays
Unpaid: read theapp.billing.notRecordedentry’sreasonin the audit log. - Checkout returns a
403:flPurchaseTokenis missing or doesn’t match the row’sOrder Reference. - No
app.billingentry at all: the webhook endpoint is missing the checkout events, or its deliveries are rejected (look for anapp.billing.notRecordedentry about the signing secret).
A monthly membership for signed-in members
Goal: a signed-in member subscribes to a monthly plan, the project shows whether the membership is active, and the member manages it in Stripe’s billing portal.
Prerequisites:
- Keys and a webhook with the subscription events (Before you start).
- A sign-in that
fliplet-paymentsrecognizes: a data source login whose data source validates users by email, or SAML2. Google, Microsoft, Apple and other OAuth sign-ins don’t count. - The billing portal turned on in Stripe’s settings.
Steps:
-
Create or find the member’s Stripe customer when the screen loads, so the Subscribe click only opens checkout:
var memberCustomer = null; Fliplet.Payments.Customers.create({}).then(function (customer) { memberCustomer = customer; // the Stripe customer for the signed-in member document.querySelector('#subscribe').disabled = false; }).catch(function (error) { // 401 when nobody is signed in with a login fliplet-payments recognizes console.error('Could not load the member:', Fliplet.parseError(error)); }); -
Subscribe from a button click:
document.querySelector('#subscribe').addEventListener('click', function () { Fliplet.Payments.Checkout.create({ mode: 'subscription', customer: memberCustomer.id, line_items: [{ quantity: 1, price_data: { currency: 'usd', unit_amount: 1500, // $15.00 a month recurring: { interval: 'month' }, product_data: { name: 'Monthly membership' } } }] // With a catalog, use a recurring Price ID instead of price_data: // line_items: [{ price: 'price_1Q2w3E4r5T6y7U8i', quantity: 1 }] }).then(function () { showMessage('Welcome! Your membership is active.'); }).catch(handleCheckoutError); }); -
Check whether the membership is active from the subscription events:
// Stripe can deliver events out of order, so the last one received isn't // always the newest. A canceled subscription can't come back, so a late // event never revives one. var ENDED = ['canceled', 'incomplete_expired']; // Read every page: a cancellation could be on any of them. function getAllEvents(offset, collected) { return Fliplet.Payments.Customers.getLogs({ limit: 1000, offset: offset }).then(function (page) { var events = collected.concat(page); return page.length < 1000 ? events : getAllEvents(offset + 1000, events); }); } function isMembershipActive() { return getAllEvents(0, []).then(function (logs) { var subscriptions = {}; // the latest known state of each subscription, by ID logs .filter(function (log) { return /^customer\.subscription\./.test(log.data.type); }) .forEach(function (log) { // oldest received first var subscription = log.data.object; var known = subscriptions[subscription.id]; if (!known || ENDED.indexOf(known.status) === -1) { subscriptions[subscription.id] = subscription; } }); return Object.keys(subscriptions).some(function (id) { return ['active', 'trialing'].indexOf(subscriptions[id].status) !== -1; }); }); }getLogs()returns events for the signed-in member only, oldest received first. A status that changes back and forth, such asactiveandpast_due, can show the older value until the next event arrives. -
Let members manage or cancel the subscription:
document.querySelector('#manage').addEventListener('click', function () { Fliplet.Payments.Customers.openBillingPortal().then(function () { // The member has returned from Stripe's billing portal }); });
Verification: the subscription appears under the customer in Stripe, and isMembershipActive() resolves with true once the customer.subscription.created event arrives.
Common pitfalls:
Customers.create()rejects with a 401: the member isn’t signed in with a loginfliplet-paymentsrecognizes. A Studio account doesn’t count.isMembershipActive()staysfalse: the webhook endpoint is missing the subscription events.- The billing portal fails to open: its settings haven’t been saved in Stripe.
API reference
Configuration.exists()
Resolves with true when payments are configured, otherwise false. It reads the project’s hasPayments setting, which is set on the Studio project when keys are saved, so a published project sees it after you republish. Makes no request.
Configuration.update(options)
Saves the project’s Stripe keys. Requires a Studio session for a user of the project’s organization.
provider(String, required):'stripe'providerPublicKey(String, required): Stripe publishable keyproviderPrivateKey(String, required): Stripe secret keyproductsDataSourceId(Number, optional): the data sourceProducts.get()reads
Resolves with { webhookUrl }, the URL to add as a webhook endpoint in Stripe. Throws synchronously when provider or either key is missing. Fields you leave out keep their saved values.
Configuration.updateSigningSecret(secret)
Saves the webhook endpoint’s signing secret (whsec_...). Requires a Studio session for a user of the project’s organization. Resolves with undefined.
Products.get()
Resolves with an array of the products data source’s rows, as plain objects of column values (for example { Name: 'Monthly membership', Price: 15, 'Price ID': 'price_1Q2w...' }). Rejects when no products data source is configured.
Checkout.create(options)
Creates a Stripe Checkout Session and opens Stripe’s hosted checkout. Call it from a click handler, with no slow work before it.
- Accepts any Checkout Session option except
success_urlandcancel_url, which Fliplet sets. client_reference_id(String): the order row’s ID, for payment recording.flPurchaseToken(String): the row’s secret reference, for proving ownership. Not sent to Stripe.
Resolves with { id, currency, customer, customer_details, customer_email } when checkout completes. Rejects as described in Handling the result. No sign-in is required.
Customers.create(options)
Creates or finds the Stripe customer for the end user signed in to the project, by their email. Any email you pass is ignored. name (String, optional) is used when creating a new customer. Resolves with the Stripe customer object, including id.
Requires an end user signed in with a login fliplet-payments recognizes:
- a data source login for this project, its organization or another project in it, when that data source validates users by email;
- SAML2 for this project or another project in its organization.
Google, Microsoft, Apple and other OAuth sign-ins, and Studio accounts, don’t count. Otherwise it rejects with 401 (“Please sign in to manage billing”). For a guest checkout, pass customer_email to Checkout.create() instead.
Customers.getLogs(options)
Resolves with the stored Stripe webhook events for the signed-in end user’s Stripe customer. Requires the same sign-in as Customers.create(). Resolves with [] when that user has no Stripe customer yet.
limit(Number, default 100)offset(Number, default 0)where.type(String, optional): one Stripe event type, such ascustomer.subscription.updated
Each log has type: 'app.billing', createdAt and data. data.object is the Stripe object the event carried (a subscription, a Checkout Session), data.type is the event type and data.customerId is the Stripe customer ID. Results come oldest received first. Stripe can deliver events out of order, so that isn’t always the order they happened, and createdAt is when Fliplet received the event. Only events your webhook endpoint subscribes to are stored. See the membership example for working out a subscription’s state.
Fliplet.Payments.Customers.getLogs({
limit: 30,
where: { type: 'customer.subscription.updated' }
}).then(function (logs) {
logs.sort(function (a, b) { return new Date(b.createdAt) - new Date(a.createdAt); });
logs.forEach(function (log) {
console.log(log.createdAt, log.data.object.status); // the subscription's status at that event
});
});
Customers.openBillingPortal()
Opens Stripe’s billing portal for the signed-in end user’s Stripe customer. Requires the same sign-in as Customers.create(), a Stripe customer created first with Customers.create(), and portal settings saved in Stripe. Resolves when the user returns to the project.
Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| Checkout rejects with a Stripe message such as “Received unknown parameter” | Your Stripe account’s API version doesn’t accept that option | Check the option in the Stripe API reference for your account’s version, or leave it out |
Checkout rejects with a 403 |
The row named by client_reference_id isn’t the buyer’s, or flPurchaseToken is missing or wrong |
Send the row’s own ownershipTokenColumn value as flPurchaseToken |
| Checkout rejects with “Payments have not been configured for this app” | No keys are saved for this project, for example in a copied project | Save keys with Configuration.update() |
Customers.create(), getLogs() or openBillingPortal() rejects with a 401 |
Nobody is signed in with a login fliplet-payments recognizes |
Use a data source login that validates by email, or SAML2, or use customer_email for guests |
The checkout window doesn’t open and the promise rejects with paymentIncomplete |
The browser blocked the pop-up because checkout didn’t start straight from a click | Do slow work before the click, so the handler only calls Checkout.create() |
| The order row stays unpaid | Payment recording refused the payment | Read the app.billing.notRecorded entry in the project’s audit log |
| Stripe shows failed webhook deliveries | The saved signing secret is from another endpoint or mode | Save the signing secret of this endpoint with Configuration.updateSigningSecret() |