Vorbly Code | WIX STRIPE INTEGRATION - AUTHORIZE PAYMENTS

Vorbly <Code>

CODING MADE EASY WITH VORBLY

WIX STRIPE INTEGRATION - AUTHORIZE PAYMENTS

Starting a travel booking website? This tutorial will show you how to integrate Stripe Payment APIs into your Wix website for payment authorization. You can authorize credit card payments then charge your customers at a later date. We will provide you with the webpage elements and sample codes required to implement this feature.

THE DEMO

1/2

THE ELEMENTS

The Page

Text Elements​

  • Product Name ID: #product

  • Description ID: #description

  • Amount ID: #amount

Button Elements

  • Book Now Button: #BookNow

Stripe API Keys

Go to www.stripe.com and retrieve two API keys.

  • Publishable Key

  • Secret Key

The Lightbox

Light Box: Payment

User Inputs

  • Cardholder Name Field: #cardname

  • Card Number Field: #cardnum

  • Expiry Month Field: #month

  • Expiry Year Field: #year

  • Card CVC Field: #cvc

Text Elements

  • Error Message: #errortext

Button Elements

  • Payment Button: #SubmitButton

The Database

Create a database Payments (database1). No fields required.

THE CODE

Page Code

import wixWindow from "wix-window";

$w.onReady(function () {

    $w("#BookNow").onClick((event, $w) => {

        var amm = $w("#amount").text

        var data = {

            amount: $w("#amount").text,

            itemName: $w("#product").text,

            description: $w("#description").text

        }

        wixWindow.openLightbox("Payment", data)

    });

});

Lightbox Code

import { createToken, encodeCard } from "public/stripeAPI.js";
import { charge } from "backend/stripeProxy";
import wixWindow from "wix-window";
import wixData from "wix-data";

 

var pmtdata;

$w.onReady(function () {
    $w("#SubmitButton").onClick((event, $w) => {
        payNow();
    });


    pmtdata = wixWindow.lightbox.getContext();
    changeState(pmtdata.amount, pmtdata.description);
    $w("#SubmitButton").label = "Pay " + pmtdata.amount + "$";
});


var payment;

function payNow() {
    var accepted = false;
    createToken(encodeCard(createCard())).then((token) => {
        charge(token, payment).then((chargeResponse) => {
            if (chargeResponse.id !== undefined) {
                $w("#errortext").show();
                $w("#errortext").text = "Sucessful Payment";
                accepted = true;
                var item = {
                    "amount": pmtdata.amount,
                    "productName": pmtdata.itemName,
                    "productDesc": pmtdata.description,
                    "stripeChargeId": chargeResponse.id
                }
                wixData.insert("Payments", item)
            }
        });
    });


    setTimeout(function () {
        if (!accepted) {
            $w("#errortext").show();
            $w("#errortext").text = "Payment Declined";
        }
    }, 3200);
}

function createCard() {
    return {
        "name": $w("#cardname").value,
        "number": $w("#cardnum").value,
        "cvc": $w("#cvc").value,
        "exp_year": $w("#year").value,
        "exp_month": $w("#month").value
    };
}

function changeState(x, y) {
    payment = {
        "amount": (x * 100),
        "currency": "USD",
        "description": y,

        "capture": "false"
    }
}

Public Code

// stripeAPI.js //

 

import { fetch } from "wix-fetch";

export async function createToken(card) {

    const apiKey = "Publishable Key";

    const response = await fetch("https://api.stripe.com/v1/tokens", {

        method: "post",

        headers: {

            "Content-Type": "application/x-www-form-urlencoded",

            "Authorization": "Bearer " + apiKey

        },

        body: card

    });

    if (response.status >= 200 && response.status < 300) {

        const json = await response.json();

        return json.id;

    }

    const responseText = await response.text();

    console.log(responseText);

    return response.status;

}

export function encodeCard(card) {

    let encoded = "";

    for (let [k, v] of Object.entries(card)) {

        encoded = encoded.concat("card[", k, "]=", encodeURI(v), "&");

    }

    return encoded.substr(0, encoded.length - 1);

}

Back-End Code

// stripeProxy.jsw //

 

import { fetch } from "wix-fetch";

export async function charge(token, payment) {

    const cart = payment;

    const apiKey = "Secret Key";

    const response = await fetch("https://api.stripe.com/v1/charges", {

        method: "post",

        headers: {

            "Content-Type": "application/x-www-form-urlencoded",

            "Authorization": "Bearer " + apiKey

        },

        body: encodeBody(token, cart)

    });

    if (response.status >= 200 && response.status < 300) {

        return await response.json();

    }

    return await response.text();

}

 

function encodeBody(token, cart) {

    let encoded = "";

    for (let [k, v] of Object.entries(cart)) {

        encoded = encoded.concat(k, "=", encodeURI(v), "&");

    }

    encoded = encoded.concat("source=", encodeURI(token));

    return encoded;

}

COMMENTS

I'm a paragraph. Click here to add your own text and edit me. It's easy.

No comments. Be the first to leave a comment.

I have 2 questions, first question is, I supposed I can add 2 more user inputs-right? Second question is if the
database 1's fields are no required, how can I retrieve all the user inputs from the database?

Hock Lian

May 03, 2019

0

Hi Hock Lian,

Thanks for your comments. Just to clarify your questions.

Is your first question is whether you can add 2 more user inputs to the payment info lightbox?
You can add additional user fields to your payment info lightbox. However, Stripe will only require information such as credit card number and expiry date to process the payments. As such, you will not need to send these additional information to Stripe. You can insert these information to your Payments dataset for your reference.

Your second question is how to retrieve all user inputs from the Payments database (dataset1)? First option, you can retrieve the information from your Wix Editor (if you are the admin). Second option, you can create a dashboard with a repeater displaying all the payment information.

I hope this answers your questions. Thank you!

Andrew (Vorbly)

May 27, 2019

1

I've followed every instruction, everything works until some point where when I fill the form with the card details, I press the button "Pay Now" and then i get Payment Declined message which obviosly comes from the following part of the code:
setTimeout(function () {
if (!accepted) {
$w("#errortext").show();
$w("#errortext").text = "Payment Declined";
}
}, 3200);
}

Can you please explain what this exactly means? TIA

Laura

Jul 22, 2019

1

Hi Laura,

Did you manage to get this to work? There could be several reasons why you are getting a decline transaction.

1. Did you use one of Stripe's test cards? Transactions will only be approved if you use any one of their test card details. See the full list: https://stripe.com/docs/testing#cards
2. Are you seeing a (decline) transaction in Stripe? What was the decline reason?

Hope this helps you identify the cause of your issue.

Andrew (Vorbly)

Aug 17, 2019

0

I want to have a page with fields that user can input info like a form application and connected to a database collection. I'm not sure if I clicked the button of the "Book Now" the lightbox open for payment submission, does it connect to the database at the same time?

Hock Lian

Jan 03, 2020

0

WEB DESIGN & DEVELOPMENT SOLUTIONS

GET PROFESSIONAL HELP