简体   繁体   中英

Integrating Stripe Checkout in Netlify

I am trying to integrate Stripe Checkout in Netlify Website. My website uses HTML, CSS and Javascript. I am trying to build a server in Node.js but the code I have is in Express Node and AWS Lambda does not support it. I would really appreciate it if someone could help me modify the code so it works with AWS Lambda.

Client Side Javascript "checkoutstripe.js"

var stripe = Stripe('pk_test_TYooMQauvdEDq54NiTphI7jx');
  var checkoutButton = document.getElementById('checkout-button');

  checkoutButton.addEventListener('click', function() {
    // Create a new Checkout Session using the server-side endpoint you
    // created in step 3.
    fetch('/create-checkout-session', {
      method: 'POST',
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(session) {
      return stripe.redirectToCheckout({ sessionId: session.id });
    })
    .then(function(result) {
      // If `redirectToCheckout` fails due to a browser or network
      // error, you should display the localized error message to your
      // customer using `error.message`.
      if (result.error) {
        alert(result.error.message);
      }
    })
    .catch(function(error) {
      console.error('Error:', error);
    });
  });

Server Side Node.js Code "server.js"

const express = require('express');
const app = express();

// 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_4eC39HqLyjWDarjtT1zdp7dc');

app.post('/create-checkout-session', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    payment_method_types: ['card'],
    line_items: [
      {
        price_data: {
          currency: 'usd',
          product_data: {
            name: 'T-shirt',
          },
          unit_amount: 2000,
        },
        quantity: 1,
      },
    ],
    mode: 'payment',
    success_url: 'https://example.com/success',
    cancel_url: 'https://example.com/cancel',
  });

  res.json({ id: session.id });
});

app.listen(4242, () => console.log(`Listening on port ${4242}!`));

I have tried integrating it but it doesn't work. It ends up in the following error in Console:

checkoutstripe.js:7 POST https://webmd.netlify.app/create-checkout-session 404 (anonymous) @ checkoutstripe.js:7 checkoutstripe.js:25 Error: SyntaxError: Unexpected token < in JSON at position 0

Also, can I remove the last line in server side code? The one with app.listen?

Update

I have tried modifying the server.js file and checkoutstripe.js file. But it still doesn't work. It does not load the server side code, as you can see in the error log from browser console

Server.js

const stripe = require('stripe')('sk_test_87b26c723c872');
    exports.handler = async (event) => {
      const session = await stripe.checkout.sessions.create({
        mode: 'payment',
        payment_method_types: ['card'],
        billing_address_collection: 'auto',
    
        success_url: `https://webmd.tech/success.html`,
        cancel_url: 'https://webmd.tech/cancel.html',
        line_items: [
          {
            price_data: {
              price: 'price_1He2fDAXJjHnvDU5765',
              },
            },
            quantity: 1,
          },
        ],
      });
    
      return {
        statusCode: 200,
        body: JSON.stringify({
          sessionId: session.id,
          publishableKey: 'pk_test_f273g27fg28gf',
        }),
      };
    };

CheckoutStripe.js

var checkoutButton = document.getElementById('stripebtn');
checkoutButton.addEventListener('click', CheckoutStripe);

async function CheckoutStripe() {
    const response = await fetch('/.netlify/functions/server', {
      method: 'POST',
    }).then((res) => res.json());

    const stripe = Stripe(response.publishableKey);
    const { error } = await stripe.redirectToCheckout({
      sessionId: response.sessionId,
    });

    if (error) {
      console.error(error);
    }
  }

The error in browser console is:

checkout.js:8 POST https://webmd.netlify.app/.netlify/functions/server 502 CheckoutStripe @ checkout.js:8 (index):1 Uncaught (in promise) IntegrationError: Invalid value for Stripe(): apiKey should be a string. You specified: undefined. at new r ( https://js.stripe.com/v3/:1:6143 ) at re ( https://js.stripe.com/v3/:1:15579 ) at pe ( https://js.stripe.com/v3/:1:16063 ) at new dc ( https://js.stripe.com/v3/:1:184471 ) at fc ( https://js.stripe.com/v3/:1:185726 ) at HTMLAnchorElement.CheckoutStripe ( https://webmd.netlify.app/assets/js/checkout.js:12:24 )

and netlify functions landed the following error:

5:30:30 PM: 2020-10-20T12:30:30.285Z undefined ERROR Uncaught Exception {"errorType":"Runtime.UserCodeSyntaxError","errorMessage":"SyntaxError: Unexpected token ':'","stack":["Runtime.UserCodeSyntaxError: SyntaxError: Unexpected token ':'"," at _loadUserApp (/var/runtime/UserFunction.js:98:13)"," at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)"," at Object. (/var/runtime/index.js:43:30)"," at Module._compile (internal/modules/cjs/loader.js:1137:30)"," at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)"," at Module.load (internal/modules/cjs/loader.js:985:32)"," at Function.Module._load (internal/modules/cjs/loader.js:878:14)"," at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)"," at internal/main/run_main_module.js:17:47"]}

I see you used event.preventDefault(); in CheckoutStripe.js but you haven't event parameter defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM