Bootstrap FreeKB - PayPal - JavaScript frontend
PayPal - JavaScript frontend

Updated:   |  PayPal articles

First and foremost, it's important to understand that the PayPal SDK uses a client/server model, where the client is the frontend and the server is the backend.

 

For example, the frontend client could look something like this, where the data gathered in the frontend is then passed onto and processed by the backend. This is what is returned when using the paypal-button-container.

 

Or you could customize the JavaScript frontend to display something like this. This is what is returned when using multi-card-field-button.

 

paypal-button-container

For example, let's say you have the following HTML file. Notice this has "paypal-button-container".

<!DOCTYPE html>
<html>

  <head></head>
  <body>
    <div id="paypal-button-container" class="paypal-button-container"></div>
    <p id="result-message"></p>

    <script src="https://www.paypal.com/sdk/js?client-id={{paypal_client_id}}&buyer-country=US&currency=USD&components=buttons"></script>
    <script src="paypal_frontend.js"></script>
  </body>
</html>

 

In this example, you'd have the following JavaScript, which expects each paypal-button-container.

window.paypal.Buttons({createOrder: createOrderCallback, onApprove: onApproveCallback})
const cardField = window.paypal.CardFields({createOrder: createOrderCallback, onApprove: onApproveCallback})

async function createOrderCallback() {
    try {
        var response = await fetch(`/paypal/order/create`, {method: "POST", headers: {"Content-Type": "application/json" })
    } catch (error) {
        return resultMessage({ result: "failed", message: `${error}` })
    }        

    if ( response_json.result != "success" ) {
        return resultMessage({ result: "failed", message: `${JSON.stringify(response.json())}` })
    } else {
        return response_json.order_id
    }
}

async function onApproveCallback(order_id) {
    try {
        var response = await fetch(`/paypal/order/capture`, {method: "POST", headers: {"Content-Type": "application/json" }, body: JSON.stringify(order_id) })
    } catch (error) {
        return resultMessage({ result: "failed", message: `${error}` })
    }            

    if ( response.json().status != "COMPLETED" ) {
        return resultMessage({ result: "failed", message: `${JSON.stringify(response.json())}` })
    } else {
        return resultMessage({ result: "sucesss" })              
    }
}

function resultMessage(res) {
    document.location.replace(`/order?result=${res.result}`);
}

if (cardField.isEligible()) {
    cardField.render("#paypal-button-container")

    document
        .getElementById("multi-card-field-button")
        .addEventListener("click", () => {       

        	showSpinner()     

            cardField.submit()
                 .then(() => {})
                 .catch((submit_error) => {
                    console.log(`[${new Date().toJSON()}] submit_error => ${JSON.stringify(submit_error)}`)
                    resultMessage({ result: "failed", message: `${JSON.stringify(submit_error)}` })
                })
        })
}

 

The paypal-button-container should return something like this.

 

multi-card-field-button

Or let's say you have the following HTML file. Notice in this example that the HTML file has "multi-card-field-button" and is including cardfields.css.

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="https://www.paypalobjects.com/webstatic/en_US/developer/docs/css/cardfields.css"/>
  </head>
  <body>
    <div id="card-form" class="card_container align-items-center text-center">
      <div id="card-name-field-container"></div>
      <div id="card-number-field-container"></div>
      <div id="card-expiry-field-container" class="abc"></div>
      <div id="card-cvv-field-container"></div>
      <button id="multi-card-field-button" type="button">Submit Payment</button>
    </div>

    <script src="https://www.paypal.com/sdk/js?client-id={{paypal_client_id}}&currency=USD&components=buttons"></script>
    <script src="paypal_frontend.js"></script>
  </body>
</html>

 

In this example, you'd have the following JavaScript, which expects each multi-card-field-button.

window.paypal.Buttons({createOrder: createOrderCallback, onApprove: onApproveCallback})
const cardField = window.paypal.CardFields({createOrder: createOrderCallback, onApprove: onApproveCallback})

async function createOrderCallback() {
    try {
        var response = await fetch(`/paypal/order/create`, {method: "POST", headers: {"Content-Type": "application/json" })
    } catch (error) {
        return resultMessage({ result: "failed", message: `${error}` })
    }        

    if ( response_json.result != "success" ) {
        return resultMessage({ result: "failed", message: `${JSON.stringify(response.json())}` })
    } else {
        return response_json.order_id
    }
}

async function onApproveCallback(order_id) {
    try {
        var response = await fetch(`/paypal/order/capture`, {method: "POST", headers: {"Content-Type": "application/json" }, body: JSON.stringify(order_id) })
    } catch (error) {
        return resultMessage({ result: "failed", message: `${error}` })
    }            

    if ( response.json().status != "COMPLETED" ) {
        return resultMessage({ result: "failed", message: `${JSON.stringify(response.json())}` })
    } else {
        return resultMessage({ result: "sucesss" })              
    }
}

function resultMessage(res) {
    document.location.replace(`/order?result=${res.result}`);
}

if (cardField.isEligible()) {
    const nameField = cardField.NameField({ placeholder:"Name on Card" }).render("#card-name-field-container")
    const numberField = cardField.NumberField({ placeholder:"Card Number" }).render("#card-number-field-container")
    const expiryField = cardField.ExpiryField({ placeholder:"MM / YY (card expiration month/year)" }).render("#card-expiry-field-container")
    const cvvField = cardField.CVVField({ placeholder:"CVV (the 3 digit code on back of card)" }).render("#card-cvv-field-container")

    document
        .getElementById("multi-card-field-button")
        .addEventListener("click", () => {       

        	showSpinner()     

            cardField.submit()
                 .then(() => {})
                 .catch((submit_error) => {
                    console.log(`[${new Date().toJSON()}] submit_error => ${JSON.stringify(submit_error)}`)
                    resultMessage({ result: "failed", message: `${JSON.stringify(submit_error)}` })
                })
        })
}

 

 The multi-card-field-button should return something like this.

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 103ee1 in the box below so that we can be sure you are a human.