skip to Main Content

How can check if the user has paid for a specific product?

I plan to check if the purchase was successfully in my getServerSideProps() function in my page, which is redirect from check out as determined by success_url:


            const session = await stripe.checkout.sessions.create({
                line_items: list,
                mode: 'payment',
                success_url: ...,
                cancel_url: ...
            });

the check out redirect to my page and pass the ?paystate parameter which is OK or FAILED (depending if it cames from success_url and cancel_url, respectiely).
The someone can easily append this query string to end of the page or fake the http referer to pretende to have paid for the product so I need a server side
check too. How can I do that? I’ve tried:

const customers = await stripe.customers.list({ email: username });
        if (customers.data.length > 0) {
          const customerId = customers.data[0].id;
          const charges = await stripe.charges.list({ customer: customerId });
          //console.log('charges = ', charges);
          // Process the list of chargeeps
          charges.data.forEach((charge) => {
            console.log(`Charge ID: ${charge.id}, Amount: ${charge.amount}, Description: ${charge.description}`);
          });
        }

but it doesn’t show the purchases but a single subscription. I’ve done, in test mode, alot of purchases with the username I’ve passed in the argument.

How do I archive that?

2

Answers


  1. According to documentation, the best way to validate the payment is listening to Stripe webhook Apis.

    Implementing a Webhook URL allow you to receive in real time all the stripe’s events you need.

    In your case, the checkout.session.completed seems to be a good solution, this event will be triggered as soon as the payment is validated by stripe. In the Stripe dashboard you can chose and define which events you’ll be listening to.

    The event will send you all the elements you need to manage your logic after a payment (customer_id, session_id etc.)

    Login or Signup to reply.
  2. You access the line item product details by retrieving the Checkout session using expansion to include line_items in the response (not included by default):

    curl https://api.stripe.com/v1/checkout/sessions/cs_test_123abc 
    -u "sk_test_123:" 
    -d "expand[]"=line_items
    

    As for not seeing the results you expect based on your code, it’s most likely because you have many test customers using the same email (this is not a unique key or de-duplicated), and you’re checking only the first result. You need to figure out the specific customer ID of your test checkout session (i.e. cus_123) and list sessions for that customer.

    Note that you can also expand list results using eg expand[]=data.line_items.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search