如何使用 Stripe 添加多个计划层级?

问题描述 投票:0回答:1
//api/stripe
import { auth, currentUser } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { prismadb } from "@/lib/prismadb";
import { stripe } from "@/lib/stripe";
import { absoluteUrl } from "@/lib/utils";


const billingUrl = absoluteUrl("/billing");

export async function GET() {
  try {
    const { userId } = auth();
    const user = await currentUser();

    if (!userId || !user) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const userSubscription = await prismadb.userSubscription.findUnique({
      where: {
        userId,
      },
    });

    if (userSubscription && userSubscription.stripeCustomerId) {
      const stripeSession = await stripe.billingPortal.sessions.create({
        customer: userSubscription.stripeCustomerId,
        return_url: billingUrl,
      });

      return new NextResponse(JSON.stringify({ url: stripeSession.url }));
    }

    const stripeSession = await stripe.checkout.sessions.create({
      success_url: billingUrl,
      cancel_url: billingUrl,
      payment_method_types: ["card", "Paypal"],
      mode: "subscription",
      billing_address_collection: "auto",
      customer_email: user.emailAddresses[0].emailAddress,
      line_items: [
        {
          price_data: {
            currency: "USD",
            product_data: {
              name: "Plume Pro",
              description: "Gain Full Access",
            },
            unit_amount: 7999,
            recurring: {
              interval: "month",
            },
          },
          quantity: 1,
        },
        {
          price_data: {
            currency: "USD",
             product_data: {
              name: "Plume Plus",
              description: "Gain Full Access",
            },
            unit_amount: 3999,
            recurring: {
              interval: "month",
            },
          },
          quantity: 1,
        },
      ],
      metadata: {
        userId,
      },
    });

    return new NextResponse(JSON.stringify({ url: stripeSession.url }));
  } catch (error) {
    console.log("[STRIPE_GET]", error);
    return new NextResponse("Internal Error", { status: 500 });
  } 
}

"use client";

import { usePlanModal } from "@/hooks/use-plan-modal";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "../ui/dialog";
import { Separator } from "../ui/separator";
import { Button } from "../ui/button";
import { useToast } from "../ui/use-toast";
import axios from "axios";
import { useState } from "react";

export const PlanModal = () => {
  const planModal = usePlanModal();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);

  const onSubscribe = async () => {
    try {
      setLoading(true);
      const response = await axios.get("/api/stripe");

      window.location.href = response.data.url;
    } catch (error) {
      toast({
        variant: "destructive",
        description: "Oops! Something went wrong.",
      });
    } finally {
      setLoading(false);
    }
  };
  return (
    <Dialog open={planModal.isOpen} onOpenChange={planModal.onClose}>
      <DialogContent>
        <DialogHeader className="space-y-4">
          <DialogTitle className="text-center">Upgrade your Plan</DialogTitle>
          <DialogDescription className="text-center space-y-2">
            Choose a plan that meets your needs.
          </DialogDescription>
        </DialogHeader>
        <Separator />
        <div className="flex items-center justify-between">
          <p className="text-2xl font-plus font-medium">
            $39
            <span className="text-sm font-normal">.99</span>
          </p>
          <Button size="md" onClick={onSubscribe}>
            Subscribe
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};

我正在使用 Nextjs 和 Stripe 构建我的应用程序,它们有多个计划供用户订阅。这是我用不同层构建的第一个应用程序,但我未能找到使其工作的方法。因此,我寻求的帮助是了解是否有办法在单个 API 文件夹中制定计划(如果可以,如何制定),或者是否必须为每一层创建不同的 API 文件。我上面的做法只是将两层相加,结账金额为 119.98 美元。

javascript next.js stripe-payments
1个回答
0
投票

为了完整性:

  1. 如果您希望客户可以订阅多个计划 对于其中之一,您可以查看定价表。理想情况下,每个计划都会生成不同的结帐会话。

  2. 如果您想拥有 1 个多层计划,并且您的客户 可以订阅并根据其使用情况计费,您 可以使用分层定价

虽然您的问题有点不清楚,但我认为在这种情况下您需要定价表。

© www.soinside.com 2019 - 2024. All rights reserved.