Finding Stripe Subscription IDs
Finding Stripe Subscription IDs
Staysignal requires a subscription_id
to identify which subscription a user is trying to cancel. Here are ways to find and use a user's Stripe subscription ID:
From Your Database
Most applications store subscription IDs in their database after a successful Stripe subscription creation. This is the recommended approach for performance and reliability.
<script>
// Example using Node.js with Express and MongoDB
app.get('/account', async (req, res) => {
try {
// Get user ID from session/JWT
const userId = req.user.id;
// Fetch subscription from your database
const user = await User.findById(userId).populate('subscription');
const subscriptionId = user.subscription?.stripeSubscriptionId;
res.render('account', {
user,
subscriptionId // Pass to your view
});
} catch (error) {
console.error('Error fetching subscription:', error);
res.status(500).send('Server error');
}
});
</script>
Fetching from Stripe API
If you need to fetch the subscription ID directly from Stripe (not recommended for production):
<script>
// Using Stripe Node.js SDK
const stripe = require('stripe')('sk_test_your_stripe_secret_key');
async function getCustomerSubscriptions(customerId) {
try {
const subscriptions = await stripe.subscriptions.list({
customer: customerId,
status: 'active',
limit: 1
});
if (subscriptions.data.length > 0) {
return subscriptions.data[0].id; // Returns the subscription ID
}
return null;
} catch (error) {
console.error('Error fetching from Stripe:', error);
throw error;
}
}
</script>
Security Considerations
Always follow these security best practices:
Never expose your Stripe secret key in client-side code
Implement proper authentication before showing/using subscription IDs
If using the Stripe API directly, cache the results to minimize API calls
Consider using Stripe Webhooks to keep your database in sync with Stripe
Need Help?
If you encounter any issues with the integration, please contact our support team.
Last updated