Phiên kiểm tra sọc nodejs

Vì vậy, bạn vừa tạo một ứng dụng tuyệt vời và bây giờ bạn cần thực sự được trả tiền cho nó nhưng bạn không biết bắt đầu từ đâu. Điều đó thật hoàn hảo vì trong bài viết này tôi sẽ chỉ cho bạn từng bước cách thiết lập Stripe với Node. js và chấp nhận thanh toán thông qua giao diện người dùng tuyệt đẹp này

Phiên kiểm tra sọc nodejs

Trước khi bắt đầu, tôi muốn đề cập rằng tài liệu của Stripe rất tuyệt vời và tôi thực sự khuyên bạn nên sử dụng tài liệu của họ cùng với bài viết này

Nếu bạn muốn học trực quan, hãy xem phiên bản video của bài viết này

Thành lập

Bước rõ ràng đầu tiên để bắt đầu là tạo một tài khoản với Stripe. Bạn cũng cần đảm bảo rằng bạn điền tất cả thông tin về doanh nghiệp của mình (thông tin về thuế, địa chỉ, v.v. ) để đảm bảo bạn tuân thủ pháp luật trước khi chấp nhận thanh toán. Khi đã xong, bước tiếp theo là thiết lập dự án của bạn

Bạn sẽ cần một nút. js để tích hợp Stripe, vì vậy nếu bạn chưa có Node. js express server thì bạn sẽ cần làm như sau

Thiết lập máy chủ tốc hành

  1. Chạy
    // Initiate a POST request to the server
    // If the server is on a different domain than the client
    // then this needs to be the full url
    // http://localhost:3000/create-checkout-session
    fetch("/create-checkout-session", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      // Send along all the information about the items
      body: JSON.stringify({
        items: [
          {
            id: 1,
            quantity: 2,
          },
          {
            id: 2,
            quantity: 1,
          },
        ],
      }),
    })
      .then(res => {
        if (res.ok) return res.json()
        // If there is an error then make sure we catch that
        return res.json().then(e => Promise.reject(e))
      })
      .then(({ url }) => {
        // On success redirect the customer to the returned URL
        window.location = url
      })
      .catch(e => {
        console.error(e.error)
      })
    
    9 để tạo gói. json cho dự án của bạn
  2. Chạy
    // Create a post request for /create-checkout-session
    app.post("/create-checkout-session", async (req, res) => {
      try {
        // Create a checkout session with Stripe
        const session = await stripe.checkout.sessions.create({
          payment_method_types: ["card"],
          // For each item use the id to get it's information
          // Take that information and convert it to Stripe's format
          line_items: req.body.items.map(({ id, quantity }) => {
            const storeItem = storeItems.get(id)
            return {
              price_data: {
                currency: "usd",
                product_data: {
                  name: storeItem.name,
                },
                unit_amount: storeItem.priceInCents,
              },
              quantity: quantity,
            }
          }),
          mode: "payment",
          // Set a success and cancel URL we will send customers to
          // These must be full URLs
          // In the next section we will setup CLIENT_URL
          success_url: `${process.env.CLIENT_URL}/success.html`,
          cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
        })
    
        res.json({ url: session.url })
      } catch (e) {
        // If there is an error send it to the client
        res.status(500).json({ error: e.message })
      }
    })
    
    0 để cài đặt sọc, express và dotenv
  3. Tạo một tệp có tên
    // Create a post request for /create-checkout-session
    app.post("/create-checkout-session", async (req, res) => {
      try {
        // Create a checkout session with Stripe
        const session = await stripe.checkout.sessions.create({
          payment_method_types: ["card"],
          // For each item use the id to get it's information
          // Take that information and convert it to Stripe's format
          line_items: req.body.items.map(({ id, quantity }) => {
            const storeItem = storeItems.get(id)
            return {
              price_data: {
                currency: "usd",
                product_data: {
                  name: storeItem.name,
                },
                unit_amount: storeItem.priceInCents,
              },
              quantity: quantity,
            }
          }),
          mode: "payment",
          // Set a success and cancel URL we will send customers to
          // These must be full URLs
          // In the next section we will setup CLIENT_URL
          success_url: `${process.env.CLIENT_URL}/success.html`,
          cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
        })
    
        res.json({ url: session.url })
      } catch (e) {
        // If there is an error send it to the client
        res.status(500).json({ error: e.message })
      }
    })
    
    1 và bao gồm đoạn mã sau

// Load environment variables from the .env file into process.env
require("dotenv").config()

// Setup express
const express = require("express")
const app = express()
app.use(express.json())

// Setup Stripe
const stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY)

// This is the list of items we are selling
// This will most likely come from a database or JSON file
const storeItems = new Map([
  [1, { priceInCents: 10000, name: "Learn React Today" }],
  [2, { priceInCents: 15000, name: "Learn CSS Today" }],
])

// Start up our server on port 3000
app.listen(3000)

Kết nối phía khách hàng

Trước khi chúng tôi viết thêm bất kỳ mã nào cho máy chủ, chúng tôi sẽ tập trung vào cách bạn kết nối phía máy khách của ứng dụng với máy chủ. Theo tôi, cách tốt nhất để làm điều này là với một yêu cầu tìm nạp vì rất có thể máy chủ của bạn sẽ là một API mà bạn đang gọi từ ứng dụng khách của mình. Mã để làm điều này là như sau

// Initiate a POST request to the server
// If the server is on a different domain than the client
// then this needs to be the full url
// http://localhost:3000/create-checkout-session
fetch("/create-checkout-session", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  // Send along all the information about the items
  body: JSON.stringify({
    items: [
      {
        id: 1,
        quantity: 2,
      },
      {
        id: 2,
        quantity: 1,
      },
    ],
  }),
})
  .then(res => {
    if (res.ok) return res.json()
    // If there is an error then make sure we catch that
    return res.json().then(e => Promise.reject(e))
  })
  .then(({ url }) => {
    // On success redirect the customer to the returned URL
    window.location = url
  })
  .catch(e => {
    console.error(e.error)
  })

Đây là rất nhiều mã vì vậy hãy chia nhỏ chính xác những gì đang xảy ra. Trên máy khách, chúng tôi đang yêu cầu một điểm cuối trên máy chủ của chúng tôi và gửi cùng với id và số lượng của từng mặt hàng mà khách hàng muốn mua. Sau đó, nếu yêu cầu thành công, chúng tôi sẽ chuyển hướng khách hàng đến url được trả về từ API

Ghi chú quan trọng

  1. Nếu máy chủ và máy khách ở trên các miền khác nhau thì bạn sẽ cần sử dụng URL máy chủ đầy đủ khi thực hiện yêu cầu tìm nạp (
    // Create a post request for /create-checkout-session
    app.post("/create-checkout-session", async (req, res) => {
      try {
        // Create a checkout session with Stripe
        const session = await stripe.checkout.sessions.create({
          payment_method_types: ["card"],
          // For each item use the id to get it's information
          // Take that information and convert it to Stripe's format
          line_items: req.body.items.map(({ id, quantity }) => {
            const storeItem = storeItems.get(id)
            return {
              price_data: {
                currency: "usd",
                product_data: {
                  name: storeItem.name,
                },
                unit_amount: storeItem.priceInCents,
              },
              quantity: quantity,
            }
          }),
          mode: "payment",
          // Set a success and cancel URL we will send customers to
          // These must be full URLs
          // In the next section we will setup CLIENT_URL
          success_url: `${process.env.CLIENT_URL}/success.html`,
          cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
        })
    
        res.json({ url: session.url })
      } catch (e) {
        // If there is an error send it to the client
        res.status(500).json({ error: e.message })
      }
    })
    
    2 thay vì
    // Create a post request for /create-checkout-session
    app.post("/create-checkout-session", async (req, res) => {
      try {
        // Create a checkout session with Stripe
        const session = await stripe.checkout.sessions.create({
          payment_method_types: ["card"],
          // For each item use the id to get it's information
          // Take that information and convert it to Stripe's format
          line_items: req.body.items.map(({ id, quantity }) => {
            const storeItem = storeItems.get(id)
            return {
              price_data: {
                currency: "usd",
                product_data: {
                  name: storeItem.name,
                },
                unit_amount: storeItem.priceInCents,
              },
              quantity: quantity,
            }
          }),
          mode: "payment",
          // Set a success and cancel URL we will send customers to
          // These must be full URLs
          // In the next section we will setup CLIENT_URL
          success_url: `${process.env.CLIENT_URL}/success.html`,
          cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
        })
    
        res.json({ url: session.url })
      } catch (e) {
        // If there is an error send it to the client
        res.status(500).json({ error: e.message })
      }
    })
    
    3)
  2. Không bao giờ gửi thông tin giá từ máy khách đến máy chủ. Vì khách hàng có quyền truy cập vào mã khách hàng nên họ có thể thay đổi thông tin về giá nếu chúng tôi gửi mã đó từ khách hàng. Đây là lý do tại sao mọi thứ được thực hiện với id trên máy khách và máy chủ xử lý tất cả việc tích hợp và định giá Stripe

Kết nối phía máy chủ

Bây giờ chúng tôi có thể thực hiện yêu cầu từ máy khách đến máy chủ trên một điểm cuối có tên là

// Create a post request for /create-checkout-session
app.post("/create-checkout-session", async (req, res) => {
  try {
    // Create a checkout session with Stripe
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      // For each item use the id to get it's information
      // Take that information and convert it to Stripe's format
      line_items: req.body.items.map(({ id, quantity }) => {
        const storeItem = storeItems.get(id)
        return {
          price_data: {
            currency: "usd",
            product_data: {
              name: storeItem.name,
            },
            unit_amount: storeItem.priceInCents,
          },
          quantity: quantity,
        }
      }),
      mode: "payment",
      // Set a success and cancel URL we will send customers to
      // These must be full URLs
      // In the next section we will setup CLIENT_URL
      success_url: `${process.env.CLIENT_URL}/success.html`,
      cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
    })

    res.json({ url: session.url })
  } catch (e) {
    // If there is an error send it to the client
    res.status(500).json({ error: e.message })
  }
})
3. Bước tiếp theo đối với chúng tôi là tạo điểm cuối này trên máy chủ của chúng tôi và trả lại URL hợp lệ cho máy khách bằng cách thêm mã sau vào máy chủ của chúng tôi. tập tin js

// Create a post request for /create-checkout-session
app.post("/create-checkout-session", async (req, res) => {
  try {
    // Create a checkout session with Stripe
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      // For each item use the id to get it's information
      // Take that information and convert it to Stripe's format
      line_items: req.body.items.map(({ id, quantity }) => {
        const storeItem = storeItems.get(id)
        return {
          price_data: {
            currency: "usd",
            product_data: {
              name: storeItem.name,
            },
            unit_amount: storeItem.priceInCents,
          },
          quantity: quantity,
        }
      }),
      mode: "payment",
      // Set a success and cancel URL we will send customers to
      // These must be full URLs
      // In the next section we will setup CLIENT_URL
      success_url: `${process.env.CLIENT_URL}/success.html`,
      cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
    })

    res.json({ url: session.url })
  } catch (e) {
    // If there is an error send it to the client
    res.status(500).json({ error: e.message })
  }
})

Bây giờ mã này phức tạp hơn một chút vì vậy hãy để tôi chia nhỏ nó. Về cơ bản, chúng tôi có một điểm cuối đang lấy tất cả thông tin về mặt hàng từ khách hàng của chúng tôi. Thông tin này ở dạng đối tượng JSON có khóa

// Initiate a POST request to the server
// If the server is on a different domain than the client
// then this needs to be the full url
// http://localhost:3000/create-checkout-session
fetch("/create-checkout-session", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  // Send along all the information about the items
  body: JSON.stringify({
    items: [
      {
        id: 1,
        quantity: 2,
      },
      {
        id: 2,
        quantity: 1,
      },
    ],
  }),
})
  .then(res => {
    if (res.ok) return res.json()
    // If there is an error then make sure we catch that
    return res.json().then(e => Promise.reject(e))
  })
  .then(({ url }) => {
    // On success redirect the customer to the returned URL
    window.location = url
  })
  .catch(e => {
    console.error(e.error)
  })
0 chứa một mảng các mục có
// Initiate a POST request to the server
// If the server is on a different domain than the client
// then this needs to be the full url
// http://localhost:3000/create-checkout-session
fetch("/create-checkout-session", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  // Send along all the information about the items
  body: JSON.stringify({
    items: [
      {
        id: 1,
        quantity: 2,
      },
      {
        id: 2,
        quantity: 1,
      },
    ],
  }),
})
  .then(res => {
    if (res.ok) return res.json()
    // If there is an error then make sure we catch that
    return res.json().then(e => Promise.reject(e))
  })
  .then(({ url }) => {
    // On success redirect the customer to the returned URL
    window.location = url
  })
  .catch(e => {
    console.error(e.error)
  })
1 và
// Initiate a POST request to the server
// If the server is on a different domain than the client
// then this needs to be the full url
// http://localhost:3000/create-checkout-session
fetch("/create-checkout-session", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  // Send along all the information about the items
  body: JSON.stringify({
    items: [
      {
        id: 1,
        quantity: 2,
      },
      {
        id: 2,
        quantity: 1,
      },
    ],
  }),
})
  .then(res => {
    if (res.ok) return res.json()
    // If there is an error then make sure we catch that
    return res.json().then(e => Promise.reject(e))
  })
  .then(({ url }) => {
    // On success redirect the customer to the returned URL
    window.location = url
  })
  .catch(e => {
    console.error(e.error)
  })
2

Điều đầu tiên chúng tôi làm là gọi

// Initiate a POST request to the server
// If the server is on a different domain than the client
// then this needs to be the full url
// http://localhost:3000/create-checkout-session
fetch("/create-checkout-session", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  // Send along all the information about the items
  body: JSON.stringify({
    items: [
      {
        id: 1,
        quantity: 2,
      },
      {
        id: 2,
        quantity: 1,
      },
    ],
  }),
})
  .then(res => {
    if (res.ok) return res.json()
    // If there is an error then make sure we catch that
    return res.json().then(e => Promise.reject(e))
  })
  .then(({ url }) => {
    // On success redirect the customer to the returned URL
    window.location = url
  })
  .catch(e => {
    console.error(e.error)
  })
3 nhận một đối tượng duy nhất chứa tất cả thông tin để kiểm tra

  1. // Initiate a POST request to the server
    // If the server is on a different domain than the client
    // then this needs to be the full url
    // http://localhost:3000/create-checkout-session
    fetch("/create-checkout-session", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      // Send along all the information about the items
      body: JSON.stringify({
        items: [
          {
            id: 1,
            quantity: 2,
          },
          {
            id: 2,
            quantity: 1,
          },
        ],
      }),
    })
      .then(res => {
        if (res.ok) return res.json()
        // If there is an error then make sure we catch that
        return res.json().then(e => Promise.reject(e))
      })
      .then(({ url }) => {
        // On success redirect the customer to the returned URL
        window.location = url
      })
      .catch(e => {
        console.error(e.error)
      })
    
    4. Điều này có một loạt tất cả các phương thức thanh toán được chấp nhận như chuyển khoản ngân hàng hoặc thẻ tín dụng. Đối với hầu hết các trường hợp, bạn chỉ cần để lại giá trị này là
    // Initiate a POST request to the server
    // If the server is on a different domain than the client
    // then this needs to be the full url
    // http://localhost:3000/create-checkout-session
    fetch("/create-checkout-session", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      // Send along all the information about the items
      body: JSON.stringify({
        items: [
          {
            id: 1,
            quantity: 2,
          },
          {
            id: 2,
            quantity: 1,
          },
        ],
      }),
    })
      .then(res => {
        if (res.ok) return res.json()
        // If there is an error then make sure we catch that
        return res.json().then(e => Promise.reject(e))
      })
      .then(({ url }) => {
        // On success redirect the customer to the returned URL
        window.location = url
      })
      .catch(e => {
        console.error(e.error)
      })
    
    5 vì thông thường bạn chỉ muốn chấp nhận thẻ
  2. // Initiate a POST request to the server
    // If the server is on a different domain than the client
    // then this needs to be the full url
    // http://localhost:3000/create-checkout-session
    fetch("/create-checkout-session", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      // Send along all the information about the items
      body: JSON.stringify({
        items: [
          {
            id: 1,
            quantity: 2,
          },
          {
            id: 2,
            quantity: 1,
          },
        ],
      }),
    })
      .then(res => {
        if (res.ok) return res.json()
        // If there is an error then make sure we catch that
        return res.json().then(e => Promise.reject(e))
      })
      .then(({ url }) => {
        // On success redirect the customer to the returned URL
        window.location = url
      })
      .catch(e => {
        console.error(e.error)
      })
    
    6. Điều này xác định xem đây sẽ là đăng ký hay thanh toán một lần. Vì bài viết này chỉ đề cập đến các khoản thanh toán một lần nên chúng tôi sẽ để phần này là
    // Initiate a POST request to the server
    // If the server is on a different domain than the client
    // then this needs to be the full url
    // http://localhost:3000/create-checkout-session
    fetch("/create-checkout-session", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      // Send along all the information about the items
      body: JSON.stringify({
        items: [
          {
            id: 1,
            quantity: 2,
          },
          {
            id: 2,
            quantity: 1,
          },
        ],
      }),
    })
      .then(res => {
        if (res.ok) return res.json()
        // If there is an error then make sure we catch that
        return res.json().then(e => Promise.reject(e))
      })
      .then(({ url }) => {
        // On success redirect the customer to the returned URL
        window.location = url
      })
      .catch(e => {
        console.error(e.error)
      })
    
    7
  3. // Initiate a POST request to the server
    // If the server is on a different domain than the client
    // then this needs to be the full url
    // http://localhost:3000/create-checkout-session
    fetch("/create-checkout-session", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      // Send along all the information about the items
      body: JSON.stringify({
        items: [
          {
            id: 1,
            quantity: 2,
          },
          {
            id: 2,
            quantity: 1,
          },
        ],
      }),
    })
      .then(res => {
        if (res.ok) return res.json()
        // If there is an error then make sure we catch that
        return res.json().then(e => Promise.reject(e))
      })
      .then(({ url }) => {
        // On success redirect the customer to the returned URL
        window.location = url
      })
      .catch(e => {
        console.error(e.error)
      })
    
    8. Đây là URL chúng tôi sẽ hướng khách hàng đến sau khi thanh toán thành công
  4. // Initiate a POST request to the server
    // If the server is on a different domain than the client
    // then this needs to be the full url
    // http://localhost:3000/create-checkout-session
    fetch("/create-checkout-session", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      // Send along all the information about the items
      body: JSON.stringify({
        items: [
          {
            id: 1,
            quantity: 2,
          },
          {
            id: 2,
            quantity: 1,
          },
        ],
      }),
    })
      .then(res => {
        if (res.ok) return res.json()
        // If there is an error then make sure we catch that
        return res.json().then(e => Promise.reject(e))
      })
      .then(({ url }) => {
        // On success redirect the customer to the returned URL
        window.location = url
      })
      .catch(e => {
        console.error(e.error)
      })
    
    9. Đây là URL mà chúng tôi sẽ hướng khách hàng đến nếu họ hủy mua hàng
  5. // Create a post request for /create-checkout-session
    app.post("/create-checkout-session", async (req, res) => {
      try {
        // Create a checkout session with Stripe
        const session = await stripe.checkout.sessions.create({
          payment_method_types: ["card"],
          // For each item use the id to get it's information
          // Take that information and convert it to Stripe's format
          line_items: req.body.items.map(({ id, quantity }) => {
            const storeItem = storeItems.get(id)
            return {
              price_data: {
                currency: "usd",
                product_data: {
                  name: storeItem.name,
                },
                unit_amount: storeItem.priceInCents,
              },
              quantity: quantity,
            }
          }),
          mode: "payment",
          // Set a success and cancel URL we will send customers to
          // These must be full URLs
          // In the next section we will setup CLIENT_URL
          success_url: `${process.env.CLIENT_URL}/success.html`,
          cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
        })
    
        res.json({ url: session.url })
      } catch (e) {
        // If there is an error send it to the client
        res.status(500).json({ error: e.message })
      }
    })
    
    0. Đây là một mảng các mặt hàng mà khách hàng đang mua. Định dạng cho từng mục hàng như sau
    • // Create a post request for /create-checkout-session
      app.post("/create-checkout-session", async (req, res) => {
        try {
          // Create a checkout session with Stripe
          const session = await stripe.checkout.sessions.create({
            payment_method_types: ["card"],
            // For each item use the id to get it's information
            // Take that information and convert it to Stripe's format
            line_items: req.body.items.map(({ id, quantity }) => {
              const storeItem = storeItems.get(id)
              return {
                price_data: {
                  currency: "usd",
                  product_data: {
                    name: storeItem.name,
                  },
                  unit_amount: storeItem.priceInCents,
                },
                quantity: quantity,
              }
            }),
            mode: "payment",
            // Set a success and cancel URL we will send customers to
            // These must be full URLs
            // In the next section we will setup CLIENT_URL
            success_url: `${process.env.CLIENT_URL}/success.html`,
            cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
          })
      
          res.json({ url: session.url })
        } catch (e) {
          // If there is an error send it to the client
          res.status(500).json({ error: e.message })
        }
      })
      
      1. Đây là đối tượng chứa các thông tin về sản phẩm như tên, giá. Điều quan trọng cần lưu ý là tất cả giá trong Stripe được xác định bằng xu nên một mặt hàng 10 đô la sẽ có
      // Create a post request for /create-checkout-session
      app.post("/create-checkout-session", async (req, res) => {
        try {
          // Create a checkout session with Stripe
          const session = await stripe.checkout.sessions.create({
            payment_method_types: ["card"],
            // For each item use the id to get it's information
            // Take that information and convert it to Stripe's format
            line_items: req.body.items.map(({ id, quantity }) => {
              const storeItem = storeItems.get(id)
              return {
                price_data: {
                  currency: "usd",
                  product_data: {
                    name: storeItem.name,
                  },
                  unit_amount: storeItem.priceInCents,
                },
                quantity: quantity,
              }
            }),
            mode: "payment",
            // Set a success and cancel URL we will send customers to
            // These must be full URLs
            // In the next section we will setup CLIENT_URL
            success_url: `${process.env.CLIENT_URL}/success.html`,
            cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
          })
      
          res.json({ url: session.url })
        } catch (e) {
          // If there is an error send it to the client
          res.status(500).json({ error: e.message })
        }
      })
      
      2 trên 1000
    • // Initiate a POST request to the server
      // If the server is on a different domain than the client
      // then this needs to be the full url
      // http://localhost:3000/create-checkout-session
      fetch("/create-checkout-session", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        // Send along all the information about the items
        body: JSON.stringify({
          items: [
            {
              id: 1,
              quantity: 2,
            },
            {
              id: 2,
              quantity: 1,
            },
          ],
        }),
      })
        .then(res => {
          if (res.ok) return res.json()
          // If there is an error then make sure we catch that
          return res.json().then(e => Promise.reject(e))
        })
        .then(({ url }) => {
          // On success redirect the customer to the returned URL
          window.location = url
        })
        .catch(e => {
          console.error(e.error)
        })
      
      2. Đây là số lượng mặt hàng mà khách hàng muốn mua

Cuối cùng, sau khi chúng tôi tạo phiên, chúng tôi có thể lấy URL từ phiên đó và gửi cho khách hàng của mình. URL này sẽ hướng người dùng đến trang thanh toán của Stripe nơi họ có thể nhập tất cả thông tin thanh toán của mình

Hoàn thiện

Đây là tất cả mã chúng ta cần viết cho dự án, nhưng chúng ta vẫn cần hoàn tất việc thiết lập các biến môi trường của mình. Để làm điều này, chúng tôi có thể tạo một tệp có tên

// Create a post request for /create-checkout-session
app.post("/create-checkout-session", async (req, res) => {
  try {
    // Create a checkout session with Stripe
    const session = await stripe.checkout.sessions.create({
      payment_method_types: ["card"],
      // For each item use the id to get it's information
      // Take that information and convert it to Stripe's format
      line_items: req.body.items.map(({ id, quantity }) => {
        const storeItem = storeItems.get(id)
        return {
          price_data: {
            currency: "usd",
            product_data: {
              name: storeItem.name,
            },
            unit_amount: storeItem.priceInCents,
          },
          quantity: quantity,
        }
      }),
      mode: "payment",
      // Set a success and cancel URL we will send customers to
      // These must be full URLs
      // In the next section we will setup CLIENT_URL
      success_url: `${process.env.CLIENT_URL}/success.html`,
      cancel_url: `${process.env.CLIENT_URL}/cancel.html`,
    })

    res.json({ url: session.url })
  } catch (e) {
    // If there is an error send it to the client
    res.status(500).json({ error: e.message })
  }
})
4 ở thư mục gốc của máy chủ của chúng tôi. Bên trong tệp đó, chúng tôi muốn lưu trữ các cặp giá trị khóa cho khóa riêng Stripe và url máy chủ của chúng tôi

// Initiate a POST request to the server
// If the server is on a different domain than the client
// then this needs to be the full url
// http://localhost:3000/create-checkout-session
fetch("/create-checkout-session", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  // Send along all the information about the items
  body: JSON.stringify({
    items: [
      {
        id: 1,
        quantity: 2,
      },
      {
        id: 2,
        quantity: 1,
      },
    ],
  }),
})
  .then(res => {
    if (res.ok) return res.json()
    // If there is an error then make sure we catch that
    return res.json().then(e => Promise.reject(e))
  })
  .then(({ url }) => {
    // On success redirect the customer to the returned URL
    window.location = url
  })
  .catch(e => {
    console.error(e.error)
  })
8

Bây giờ để lấy khóa riêng của Stripe, bạn chỉ cần truy cập bảng điều khiển tài khoản Stripe của mình trong phần Nhà phát triển trong thanh bên và nhấp vào Khóa API. Tại đây bạn có thể xem khóa bí mật của mình. Tuy nhiên, điều quan trọng cần lưu ý là Stripe có chế độ thử nghiệm và trực tiếp, và bạn sẽ muốn đảm bảo rằng bạn nhấp vào nút chuyển đổi Xem dữ liệu thử nghiệm trong thanh bên để truy cập khóa API thử nghiệm của bạn để sử dụng trong quá trình phát triển

Với khóa API này, bạn có thể tạo các khoản phí sẽ hiển thị trong phần dữ liệu thử nghiệm của tài khoản Stripe mà không thực sự tiêu bất kỳ khoản tiền thật nào. Nếu bạn muốn thử tính phí thành công, chỉ cần sử dụng thẻ có số 4242 4242 4242 4242, ngày hết hạn trong tương lai và bất kỳ CVC nào. Stripe cũng có rất nhiều thẻ khác mà bạn có thể sử dụng để kiểm tra dẫn đến các thông báo lỗi/thành công khác nhau. Bạn có thể xem tất cả chúng ở đây

Sự kết luận

Đó là tất cả những gì cần thiết để thiết lập Stripe trong ứng dụng của bạn. Chỉ với một vài dòng mã, giờ đây bạn có thể chấp nhận thanh toán trong giao diện người dùng được thiết kế đẹp mắt do Stripe cung cấp