获得对Stripe Portal的访问

问题描述

我已经设置了一个节点服务器来管理订阅,现在我试图将连接添加到Stripe客户门户(以便在创建后可以将订阅管理外包给他们)。

说明说:

创建一个用户单击的按钮:

<form method="POST" action="/create_customer_portal_session">
    <button type="submit">Manage billing</button>
</form>

,然后为此添加端点:

// Set your secret key. Remember to switch to your live secret key in production!
// See your keys here: https://dashboard.stripe.com/account/apikeys
const stripe = require('stripe')('sk_test_yvBluFKhx8Xg1vjZVoulY8NO003U0HnRoA');

var session = await stripe.billingPortal.sessions.create({
  customer: 'cus_IETxeMQvgvY05a',return_url: 'https://example.com/account',});

因此,我采用了当前的服务器实现,并尝试对其进行更新以包括此事件:

/* Get your Stripe publishable key to initialize Stripe.js */
fetch("https://***.com:4343/setup")
  .then(function(result) {
    return result.json();
  })
  .then(function(json) {
    var publicKey = json.publicKey;
    var basicPlanId = json.basicPlan;
    var proPlanId = json.proPlan;

    var stripe = Stripe(publicKey);
    // Setup event handler to create a Checkout Session when button is clicked
    document
      .getElementById("basic-plan-btn")
      .addEventListener("click",function(evt) {
        customerEmail=document.querySelector('[name="username"]').value;
        createCheckoutSession(basicPlanId).then(function(data) {
          // Call Stripe.js method to redirect to the new Checkout page
          stripe
            .redirecttocheckout({
                  sessionId: data.sessionId,})
            .then(handleResult);
        });
      });

    // Setup event handler to create a Checkout Session when button is clicked
    document
      .getElementById("pro-plan-btn")
      .addEventListener("click",function(evt) {
        customerEmail=document.querySelector('[name="username"]').value;
        createCheckoutSession(proPlanId,customerEmail).then(function(data) {
          // Call Stripe.js method to redirect to the new Checkout page
          stripe
            .redirecttocheckout({
              sessionId: data.sessionId
            })
            .then(handleResult);
        });
      });
    
    //PART  ADDED TO CALL THE USER PORTAL
    //Setup event handler to create a Portal Sesssion when button is clicked
    document
        .getElementById("portal")
        .addEventListener("click",function(evt){
            var customerId = 'cus_IETxeMQvgvY05a';
            stripe.billingPortal.sessions.create({
                customer: 'cus_IETxeMQvgvY05a',return_url: 'https://***.com/account',});
        });
    });

但是当我尝试单击按钮时,我得到了Stripe.BillinPortal未定义。

另外两个请求工作顺利:对于每个请求,我都有一个如下定义的函数

var createCheckoutSession = function(planId,customerEmail) {
  return fetch("https://***.com:4343/create-checkout-session",{
    method: "POST",headers: {
      "Content-Type": "application/json"
    },body: JSON.stringify({
      planId: planId,customerEmail: customerEmail
    })
  }).then(function(result) {
    return result.json();
  });
};

和节点服务器上的对应处理程序是这样的:

app.post("/create-checkout-session",async (req,res) => {
  const domainURL = process.env.DOMAIN;
  const { planId,customerEmail } = req.body;
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ["card"],customer_email: customerEmail,line_items: [{price: planId,quantity: 1}],subscription_data: { 
        //items: [{ plan: planId }]
        trial_period_days: 15
    },Metadata: {'planId': planId},success_url: `${domainURL}/success.html?session_id={CHECKOUT_SESSION_ID}`,cancel_url: `${domainURL}/canceled.html`,mode: 'subscription',});

  res.send({
    sessionId: session.id
  });
});

我被困在如何使用客户门户网站做同样的事情。

解决方法

您正在尝试在前端代码中使用stripe.billingPortal.sessions,但无法使用。 (带有//PART ADDED TO CALL THE USER PORTAL的代码)

会话应改为在您的后端服务器上创建。然后,您将URL返回为前端,并可以为其设置window.location。这类似于您已经实现了用于获取CheckoutSession的后端路由的方式,只是在这里您正在获取Billing Session的url字段,并且所有前端代码需要做的就是直接重定向到它。(您不需要需要像使用redirectToCheckout一样使用Stripe前端库。