Stripe payment gateway
Tags: stripe, javascript, dev, webdev
Published: 2022-09-19 09:53:21

**Client code and server code on the same URL**

Is a common payment gateway and as a dev, you probably are required to integrate this for click commerce purposes.

You need a checkout button to make a request with.
Link a script from a Javascript file to ensure you select the button and embed functionality to it.

**Create a server** → to process the payment requests . This needs to be processed on a server away from the client side to ensure they do not manipulate the payment details.

**Create an express server**

- Set up an express server. By making a directory `mkdir server`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ghoa1q4r5glgqp86n14k.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hgueuo0u80upjfec4p0d.png)

- Set up a new project in this directory by initializing `npm init -y`
- Install express , the stripe library & dotenv library that shall be essential in loading our environment variables

- Add a dev dependency nodemon for autoreloads / restarts whenever changes are made to your server.(dynamism)

**Server.js boilerplate logic**
- Load the environment variables that you have set up in using the dotenv and config()
- Require express
- The call made when the checkout function is called is API-like and so we need to send the information in json format
- Set up stripe by requiring it.
- Declare the items in your store → this can be loaded from a DB. [ This ensures the client does not tweak product info from their end]. Products are declared in Dictionary like formats, where an ID has a respective value for product name and price. Capitalizes on the Map function.
    - The client only sends an ID to the server, and quantity . and the rest is populated by the server.
- The app should listen to the port that is taking requests. in my case, port 3000

```
require('dotenv').config()

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

//calls shall be made like apis. We need to send the data packets in json
app.use(express.json())
app.use(express.static('public'))

const stripe = require('stripe')(process.env.STRIPE_PRIVATE_KEY)


const storeItems= new Map([
    [1, {priceInCents:10000, name:"White Jordan Sneakers"}],
    [2, {priceInCents:15000, name: "Customized Airforce Sneakers"}],
])

app.post('/create-checkout-session', async(req,res)=>{
    try{
      const session =await stripe.checkout.sessions.create({
        payment_method_types: ['card'],
        mode:'payment',
        line_items: req.body.items.map(item =>{
            const storeItem = storeItems.get(item.id)
            return {
                price_data: {
                    currency:'usd',
                    product_data:{
                        name:storeItem.name
                    },
                    unit_amount: storeItem.priceInCents
                },
                quantity:item.quantity,

            }
        }),
        success_url:`${process.env.SERVER_URL}/success.html`,
        cancel_url:`${process.env.SERVER_URL}/cancel.html`
        })
        res.json({url: session.url})
    }catch(e){
        res.status(500).json({error: e.message})
    }
   
})
app.listen(3000)
```
Create a public directory, where all the client logic files are stored.
In the server javascript file, you’ll be required to define that the client side code will reside in this newly created directory.

`app.use(express.static(”public”)`

```
const button = document.getElementById("button")
button.addEventListener("click",()=>{
    fetch('/create-checkout-session',{
        method:'POST',
        headers:{
            'Content-Type':'application/json'
        },
        body: JSON.stringify({
            items: [
                {id: 1, quantity:2},
                {id:2, quantity:2}
            ]
        })           
        }).then(res => {
            if (res.ok) return res.json()
            return res.json.then(json => Promise.reject(json))
        }).then (({url })=>{
            console.log(url)
            //window.location = url
        }).catch(e=> {
            console.error(e.error)
        })
})

```
**Integrate client and server**

On the event listener (on the script js file), we have to make a request to the server , to prompt return of a URL  to a checkout page.

- In the request (parametric) , we pass in info about our purchase [id of the product , quantity etc] → we get a unique URL in return on where we’ll get the pay out.
- Within this logic, we have to define success and failure redirect mechanisms.

**Sessions**
You need to create a session, where you’re redirected on success episodes.
Here we also define the payment methods that we accept. Methods include bank transfers, cards etcetera.

**Modes**→ we define the specific transaction iterations. Could be one time payments, or subscriptions etcetera.

The success and failure urls are defined here. 

- **success **→ `$`{process.env.SERVER_URL}/success.html
- **cancel **→  `$`{process.env.SERVER_URL}/cancel.html

*We use environment variables to be able to push the same code to production. we could also however use the static way by explicitly defining the url → http://localhost:3000/success.html*

The SERVER_URL variable is declared in the .env file

SERVER_URL = [http://localhost:3000](http://localhost:3000) for the development url, and will be changed before being pushed to production.

Remember to add your .env file to the gitignore file setup to protect the info that you push on a public repo.

**Stripe PRIVATE_KEY**
You require a stripe account for this.
Have the variable stored in the .env file since you’ll not push it to your public repo.

This is all you need to have your stripe working.

[Click Here](https://github.com/elloh414) to go to my github repo for clones, forks and collabs!!

For the full [stripe code](https://github.com/Elloh414/stripe) and you could also go through the [official documentation.](https://stripe.com/docs)