Skip to content

Instantly share code, notes, and snippets.

@rishi-raj-jain
Last active November 13, 2025 17:23
Show Gist options
  • Select an option

  • Save rishi-raj-jain/7003fbd3d9ff0e4cec318c8f64939613 to your computer and use it in GitHub Desktop.

Select an option

Save rishi-raj-jain/7003fbd3d9ff0e4cec318c8f64939613 to your computer and use it in GitHub Desktop.
#!/usr/bin/env node
// Get the token from command line argument or environment variable
const PRODUCT_AMOUNT = process.env.PRODUCT_AMOUNT || 4900;
const CUSTOMER_NAME = process.env.CUSTOMER_NAME || 'Jane Doe';
const USER_TOKEN = process.env.POLAR_TOKEN || 'polar_oat_...';
const CUSTOMER_EMAIL = process.env.CUSTOMER_EMAIL || 'rishi@polar.sh';
const PRODUCT_ID = process.env.PRODUCT_ID || 'fd44360d-490d-497c-b412-e0eaa932cc27';
async function runCheckoutFlow() {
try {
// Step 1: Call the first API to create a checkout
console.log('Step 1: Creating checkout...');
const firstUrl = 'https://sandbox-api.polar.sh/v1/checkouts/';
const firstResponse = await fetch(firstUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${USER_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
allow_discount_codes: true,
require_billing_address: false,
products: [PRODUCT_ID]
})
});
if (!firstResponse.ok) {
throw new Error(`First API call failed: ${firstResponse.status} ${firstResponse.statusText}`);
}
const firstData = await firstResponse.json();
console.log('Step 1 response:', JSON.stringify(firstData, null, 2));
// Extract required values from first response
const publishableKey = firstData.payment_processor_metadata?.publishable_key;
const clientSecret = firstData.client_secret;
if (!publishableKey) {
throw new Error('publishable_key not found in payment_processor_metadata');
}
if (!clientSecret) {
throw new Error('client_secret not found in response');
}
console.log(`\nExtracted publishable_key: ${publishableKey.substring(0, 20)}...`);
console.log(`Extracted client_secret: ${clientSecret.substring(0, 20)}...`);
// Step 2: Call Stripe API with the publishable_key
console.log('\nStep 2: Calling Stripe API...');
const stripeUrl = 'https://api.stripe.com/v1/confirmation_tokens';
const stripeBodyBase = 'payment_method_data[billing_details][name]=Jane+Poe&payment_method_data[billing_details][email]=rishi%2B255%40polar.sh&payment_method_data[billing_details][address][country]=IN&payment_method_data[type]=card&payment_method_data[card][number]=4242+4242+4242+4242&payment_method_data[card][cvc]=424&payment_method_data[card][exp_year]=29&payment_method_data[card][exp_month]=04&payment_method_data[allow_redisplay]=unspecified&payment_method_data[pasted_fields]=number%2Cexp%2Ccvc&payment_method_data[payment_user_agent]=stripe.js%2F846ec90400%3B+stripe-js-v3%2F846ec90400%3B+payment-element%3B+deferred-intent%3B+autopm&payment_method_data[referrer]=https%3A%2F%2Fsandbox.polar.sh&payment_method_data[time_on_page]=86546&payment_method_data[client_attribution_metadata][client_session_id]=5c2e9168-fb9c-4cd5-a73f-e1b61cb54989&payment_method_data[client_attribution_metadata][merchant_integration_source]=elements&payment_method_data[client_attribution_metadata][merchant_integration_subtype]=payment-element&payment_method_data[client_attribution_metadata][merchant_integration_version]=2021&payment_method_data[client_attribution_metadata][payment_intent_creation_flow]=deferred&payment_method_data[client_attribution_metadata][payment_method_selection_flow]=automatic&payment_method_data[client_attribution_metadata][elements_session_config_id]=4fedbfdb-b43f-4be5-9bc3-c269c3991384&payment_method_data[client_attribution_metadata][merchant_integration_additional_elements][0]=payment&payment_method_data[client_attribution_metadata][merchant_integration_additional_elements][1]=achBankSearchResults&payment_method_data[guid]=6e2cfe69-3ae4-4095-a270-bfa80d632bdc593030&payment_method_data[muid]=95566b65-4990-49e3-bfd3-c6e4b71ffd4888f881&payment_method_data[sid]=07a59489-f6a2-4543-bb4d-abf2d5f121f48c152f&payment_method_data[radar_options][hcaptcha_token]=20000000-aaaa-bbbb-cccc-000000000002&client_context[currency]=usd&client_context[mode]=payment&client_attribution_metadata[client_session_id]=5c2e9168-fb9c-4cd5-a73f-e1b61cb54989&client_attribution_metadata[merchant_integration_source]=elements&client_attribution_metadata[merchant_integration_subtype]=payment-element&client_attribution_metadata[merchant_integration_version]=2021&client_attribution_metadata[payment_intent_creation_flow]=deferred&client_attribution_metadata[payment_method_selection_flow]=automatic&client_attribution_metadata[elements_session_config_id]=4fedbfdb-b43f-4be5-9bc3-c269c3991384&client_attribution_metadata[merchant_integration_additional_elements][0]=payment&client_attribution_metadata[merchant_integration_additional_elements][1]=achBankSearchResults';
const stripeBody = `${stripeBodyBase}&key=${encodeURIComponent(publishableKey)}&_stripe_version=2025-03-31.basil`;
const stripeResponse = await fetch(stripeUrl, {
method: 'POST',
headers: {
'accept': 'application/json',
'content-type': 'application/x-www-form-urlencoded',
'referrer': 'https://js.stripe.com/'
},
body: stripeBody
});
if (!stripeResponse.ok) {
const errorText = await stripeResponse.text();
throw new Error(`Stripe API call failed: ${stripeResponse.status} ${stripeResponse.statusText}\n${errorText}`);
}
const stripeData = await stripeResponse.json();
console.log('Step 2 response:', JSON.stringify(stripeData, null, 2));
// Extract confirmation_token_id from Stripe response
const confirmationTokenId = stripeData.id;
if (!confirmationTokenId) {
throw new Error('id not found in Stripe response');
}
console.log(`\nExtracted confirmation_token_id: ${confirmationTokenId}`);
// Step 3: Call the third API to confirm the checkout
console.log('\nStep 3: Confirming checkout...');
const thirdUrl = `https://sandbox-api.polar.sh/v1/checkouts/client/${clientSecret}/confirm`;
const thirdResponse = await fetch(thirdUrl, {
method: 'POST',
headers: {
Authorization: `Bearer ${USER_TOKEN}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
custom_field_data: {},
product_id: PRODUCT_ID,
amount: PRODUCT_AMOUNT,
customer_name: CUSTOMER_NAME,
customer_email: CUSTOMER_EMAIL,
customer_billing_address: {
country: 'IN'
},
confirmation_token_id: confirmationTokenId
})
});
if (!thirdResponse.ok) {
const errorText = await thirdResponse.text();
throw new Error(`Third API call failed: ${thirdResponse.status} ${thirdResponse.statusText}\n${errorText}`);
}
const thirdData = await thirdResponse.json();
console.log('\nStep 3 response:', JSON.stringify(thirdData, null, 2));
console.log('\n✅ All steps completed successfully!');
return thirdData;
} catch (error) {
console.error('\n❌ Error:', error.message);
if (error.stack) {
console.error('Stack:', error.stack);
}
process.exit(1);
}
}
// Run the flow
runCheckoutFlow();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment