客户门户与账单历史
集成 Stripe Customer Portal,让用户直接管理订阅并查看账单历史。
客户门户与账单历史 是 CoddyKit 上的免费 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Powered SaaS: Stripe + Auth + Billing + Deploy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Meet the Stripe Customer Portal
Welcome! In this lesson, we'll integrate the Stripe Customer Portal. This powerful tool empowers your users to manage their own billing information and subscriptions directly.
Think of it as a self-service hub for their payment details.
Empowering Your Users
The Customer Portal provides a secure, Stripe-hosted page where your users can:
- Update payment methods: Change credit cards or add new ones.
- Change subscription plans: Upgrade, downgrade, or cancel their subscription.
- View billing history: Access past invoices and receipts.
- Update billing information: Change their address or tax IDs.
This reduces support requests and improves user experience.
Quick Setup in Stripe Dashboard
Before writing code, you enable and configure the Customer Portal in your Stripe Dashboard. Go to Settings > Customer Portal.
- Customize your branding (logo, colors).
- Choose which actions users can perform (e.g., allow plan changes, cancel subscriptions).
- Set a return URL for when users finish.
These settings define the user experience.
Creating a Portal Session
To send a user to the Customer Portal, your backend needs to create a Portal Session with Stripe. This generates a unique, temporary URL for that specific customer.
The process is:
- User clicks a 'Manage Billing' button in your app.
- Your frontend calls your backend API.
- Your backend calls the Stripe API to create a
billing_portal.Session. - Stripe returns a URL, which your backend sends to your frontend.
- Your frontend redirects the user to that URL.
Backend: Generate Portal Link
Here's how your backend might create a Stripe Customer Portal session. Remember to replace YOUR_SECRET_KEY and customerId with actual values.
This example uses Java, but the logic is similar for other languages.
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.billingportal.Session;
import com.stripe.param.billingportal.SessionCreateParams;
public class Main {
public static void main(String[] args) {
// Set your secret key. Use your test key during development.
Stripe.apiKey = "sk_test_YOUR_SECRET_KEY";
// This customer ID should come from your database
// associated with the logged-in user.
String customerId = "cus_N5fK1ZlW2X3Y4Z"; // Example ID
String returnUrl = "https://your-app.com/settings/billing";
try {
SessionCreateParams params =
SessionCreateParams.builder()
.setCustomer(customerId)
.setReturnUrl(returnUrl)
.build();
Session portalSession = Session.create(params);
System.out.println("Customer Portal URL: " + portalSession.getUrl());
} catch (StripeException e) {
System.err.println("Error creating portal session: " + e.getMessage());
}
}
}Frontend: Directing Users
Once your backend provides the Customer Portal URL, your frontend simply redirects the user's browser to that link. This snippet shows a basic HTML button and JavaScript to handle the redirection.
In a real app, /api/create-portal-session would be your backend endpoint.
<!DOCTYPE html>
<html>
<head>
<title>Billing Portal</title>
</head>
<body>
<h1>My SaaS Dashboard</h1>
<p>Click below to manage your subscription.</p>
<button id="manageBilling">Manage My Billing</button>
<script>
document.getElementById('manageBilling').addEventListener('click', async () => {
try {
// Call your backend to get the portal URL
const response = await fetch('/api/create-portal-session', {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
// You might send a user ID or token here
});
const data = await response.json();
if (data.url) {
window.location.href = data.url; // Redirect!
} else {
alert('Failed to get portal URL.');
}
} catch (error) {
console.error('Error opening portal:', error);
alert('Error connecting to billing portal.');
}
});
</script>
</body>
</html>Tailoring the User Portal
The SessionCreateParams used in the backend call offers customization options:
setReturnUrl(): The URL Stripe redirects the user to after they finish in the portal. Make sure it's a valid URL in your app.setConfiguration(): For advanced control over what features are available in the portal, overriding dashboard settings.
Carefully configure these to match your application's flow.
Listening for Portal Changes
When users make changes in the Customer Portal (e.g., update their plan, change payment method), Stripe emits webhooks.
You can listen for events like customer.subscription.updated or customer.source.updated to keep your application's database in sync. This was covered in the previous lesson!
Ensure your webhook handler can process these events to reflect changes in your app.
Testing Your Portal
Always test your Customer Portal integration thoroughly:
- Use Stripe's test mode API keys and test customer IDs.
- Simulate various user actions: updating cards, changing plans, viewing invoices.
- Verify that your application correctly redirects to and from the portal.
- Check that webhooks are received and processed correctly after portal actions.
This ensures a smooth experience for your users.
Portal Link Logic
You want to provide a 'Manage Billing' button in your SaaS application. When a user clicks it, what is the correct flow to open the Stripe Customer Portal?
Recap: Self-Service Success
Great job! You've learned how to integrate the Stripe Customer Portal.
- It empowers users to manage their billing and subscriptions.
- You create a session URL from your backend via the Stripe API.
- Your frontend redirects users to this secure, Stripe-hosted page.
- Webhooks keep your app updated on portal changes.
This integration significantly enhances user experience and reduces your support overhead.
常见问题解答
「客户门户与账单历史」课时是免费的吗?
是的 — 「客户门户与账单历史」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程的其余内容,请升级到 CoddyKit PRO。 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程共包含 4 节课。
「客户门户与账单历史」这节课中我会学到什么?
集成 Stripe Customer Portal,让用户直接管理订阅并查看账单历史。 你通过在浏览器中直接运行的动手代码来练习 AI Powered SaaS: Stripe + Auth + Billing + Deploy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 AI Powered SaaS: Stripe + Auth + Billing + Deploy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。
「客户门户与账单历史」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课中编写并运行代码吗?
能。每节 AI Powered SaaS: Stripe + Auth + Billing + Deploy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 订阅管理
- 处理 Stripe Webhook
- 客户门户与账单历史
- 计量计费与按用量定价