Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html>

<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.0/jquery.validate.min.js"></script>
  <script src="https://hosted.test.paysafe.com/js/v1/latest/paysafe.min.js"></script>
</head>

<body>
  <div class="container">
    <div class="row">
      <div class="col-xs-12 col-md-4">
        <!-- CREDIT CARD FORM STARTS HERE -->
        <div class="panel panel-default credit-card-box">
          <div class="panel-heading display-table">
            <div class="row display-tr">
              <h3 class="panel-title display-td">Payment Details</h3>
              <div class="display-td">
                <img class="img-responsive pull-right" src="https://developer.paysafe.com/fileadmin/content/logos/accepted_cards_by_paysafejs.png">
              </div>
            </div>
          </div>
          <div class="panel-body">
            <form role="form" id="payment-form" method="POST" action="javascript:void(0);">
              <div class="row">
                <div class="col-xs-12">
                  <div class="form-group">
                    <label for="cardNumber">CARD NUMBER</label>
                    <div class="input-group">
                      <div class="form-control" id="cardNumber"> </div>
                      <span class="input-group-addon"><i class="fa fa-credit-card"></i></span>
                    </div>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-xs-7 col-md-7">
                  <div class="form-group">
                    <label for="cardExpiry"><span class="hidden-xs">EXPIRATION</span><span class="visible-xs-inline">EXP</span> DATE</label>
                    <div class="form-control" id="cardExpiry"></div>
                  </div>
                </div>
                <div class="col-xs-5 col-md-5 pull-right">
                  <div class="form-group">
                    <label for="cardCVC">CV CODE</label>
                    <div class="form-control" id="cardCVC"></div>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-xs-12">
                  <button class="pay btn btn-info btn-lg btn-block" type="button">Pay</button>
                </div>
              </div>
              <div class="row" style="display:none;">
                <div class="col-xs-12">
                  <p class="payment-errors"></p>
                </div>
              </div>
            </form>
          </div>
        </div>
        <!-- CREDIT CARD FORM ENDS HERE -->

      </div>

      <div class="col-xs-12 col-md-8" style="font-size: 12pt; line-height: 2em;">
        <p>
        <h1>Features:</h1>
        <ul>
          <li>As-you-type, input formatting</li>
          <li>Form field validation</li>
          <li>Graceful error feedback for declined card, etc</li>
          <li>Card brand recognition</li>
          <li>Simulates AJAX processing delay with visual feedback</li>
          <li>Creates a Paysafe credit card token</li>
        </ul>
        </p>
        <p>Be sure to replace the dummy API key with a valid Paysafe API key.</p>

        <p>Built upon: Bootstrap, jQuery,
          and <a href="https://developer.paysafe.com/en/sdks/paysafejs/overview/">paysafe.js</a>
        </p>
      </div>

    </div>
  </div>
</body>

</html>
              
            
!

CSS

              
                body {
  margin-top: 20px;
}

.form-control {
  padding: 0 6px;
}
.credit-card-box .panel-title {
  display: inline;
  font-weight: bold;
}
.credit-card-box .form-control.error {
  border-color: red;
  outline: 0;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6);
}
.credit-card-box label.error {
  font-weight: bold;
  color: red;
  padding: 2px 8px;
  margin-top: 2px;
}
.credit-card-box .payment-errors {
  font-weight: bold;
  color: red;
  padding: 2px 8px;
  margin-top: 12px;
}
.credit-card-box label {
  display: block;
}

.credit-card-box .display-tr {
  display: table-row;
}
.credit-card-box .display-td {
  display: table-cell;
  vertical-align: middle;
  width: 50%;
}

.credit-card-box .panel-heading img {
  min-width: 180px;
  border-style: solid;
  border-width: 3px;
  border-color: white;
  box-shadow: 3px 3px 5px #d3d3d3;
}

              
            
!

JS

              
                // Base 64 encoded version of the Single-Use-Token API key.
// Create the key below by concatenating the API username and password
// separated by a colon and Base 64 encoding the result
const API_KEY =
  "YXRsYXNfdGVzdGluZ19wdWJsaWM6Qi1xYTItMC02MWU2YTY5Zi0wLTMwMmMwMjE0MmI2OTY1ZjM0ZDZkMWViMGZlNmVmYzNhMGU4Yjc0MjQwMjgwYTg0NDAyMTQ3NTcxODkxNzhiMjE0YjhjMzk4NzFiNTA2YjAwMjg2MDNhMGQxNzQ3";

var $form = $("#payment-form");
$form.find(".pay").prop("disabled", true);
const options = {
  currencyCode: "USD",
  accounts: {
    default: 1002316200
  },
  environment: "TEST",
  fields: {
    cardNumber: {
      selector: "#cardNumber",
      placeholder: "****************",
      separator: " "
    },
    cvv: {
      selector: "#cardCVC",
      placeholder: "****",
      mask: false,
      optional: false
    },
    expiryDate: {
      selector: "#cardExpiry",
      placeholder: "**/**"
    }
  },
  style: {
    input: {
      "font-family": "robotoregular,Helvetica,Arial,sans-serif",
      "font-weight": "normal",
      "font-size": "14px",
      "line-height": "14px"
    },

    ".valid:focus": {
      color: "green"
    }
  }
};

let instance;

// Calling async function setup (part of the merchants' website)
setup()
  .then((inst) => {
    instance = inst;
    console.log("Successfully showed payment methods.");
    // Check if CARD payment method is available.
    if (!instance.paymentMethods.card?.error) {
      addEventListeners();
      var payButton = $form.find(".pay");
      payButton.bind("click", tokenize);
    }
  })
  .catch((error) => {
    console.log(error);
    $form.find(".pay").html("Try again").prop("disabled", false);
    /* Show Paysafe errors on the form */
    $form.find(".payment-errors").text(error.displayMessage);
    $form.find(".payment-errors").closest(".row").show();
  });

/**
 * This function invocation can be replaced with chain promises.
 * Usually async/await syntax is used for its simplicity.
 *
 * paysafe.fields.setup(API_KEY, options)
 *      .then(instance => {
 *          ...
 *          return instance.show()})
 *      .then(paymentMethods => {
 *          ...
 *      })
 *      .catch(error => {
 *          ...
 *      })
 *
 *
 * OR
 *
 *  paysafe.fields.setup(API_KEY, options)
 *      .then(instance => {
 *          ...
 *          instance.show()
 *            .then(paymentMethods => {
 *                ...
 *            })
 *      })
 *      .catch(error => {
 *          ...
 *      })
 *
 */
async function setup() {
  const instance = await paysafe.fields.setup(API_KEY, options);

  console.log("Setup insance completed.");
  console.log(instance);

  const paymentMethods = await instance.show();

  console.log("Instance showed payment methods.");
  console.log(paymentMethods);

  return instance;
}

function tokenize() {
  const tokenizationOptions = {
    amount: 14000,
    merchantRefNum: generateGuid(),
    transactionType: "PAYMENT",
    paymentType: "CARD",
    // Values can be IFRAME and NEW_TAB
    openAs: "IFRAME",
    customerDetails: {
      // Required for 3DS
      holderName: "John Smith",
      billingDetails: {
        country: "US",
        zip: "90210",
        street: "Oak Fields 6",
        city: "ca",
        state: "CA"
      },
      profile: {
        firstName: "John",
        lastName: "Smith",
        email: "john@smith.com"
      }
    },
    threeDs: {
      authenticationPurpose: "PAYMENT_TRANSACTION",
      deviceChannel: "BROWSER",
      merchantUrl: "https://codepen.io/paysafe/pen/qBVNVNW",
      useThreeDSecureVersion2: true,
      maxAuthorizationsForInstalmentPayment: 12,
      billingCycle: {
        endDate: "2020-09-21",
        frequency: 92
      },
      profile: {
        email: "test@test.com",
        phone: "0123456789",
        cellPhone: "0123456789"
      },
      electronicDelivery: {
        email: "example@example.com",
        isElectronicDelivery: true
      },
      messageCategory: "PAYMENT",
      requestorChallengePreference: "NO_PREFERENCE",
      transactionIntent: "GOODS_OR_SERVICE_PURCHASE",
      initialPurchaseTime: "2019-01-21T14:47:31Z", //
      orderItemDetails: {
        preOrderItemAvailabilityDate: "2014-01-26",
        reorderItemsIndicator: "FIRST_TIME_ORDER",
        shippingIndicator: "SHIP_TO_BILLING_ADDRESS",
        preOrderPurchaseIndicator: "MERCHANDISE_AVAILABLE"
      },
      purchasedGiftCardDetails: {
        amount: 1234,
        count: 10,
        currency: "USD"
      },
      userAccountDetails: {
        addCardAttemptsForLastDay: 1,
        changedDate: "2014-01-26",
        changedRange: "DURING_TRANSACTION",
        createdDate: "2014-01-26",
        createdRange: "NO_ACCOUNT",
        passwordChangedDate: "2014-01-26",
        passwordChangedRange: "NO_CHANGE",
        totalPurchasesSixMonthCount: 1,
        transactionCountForPreviousDay: 1,
        transactionCountForPreviousYear: 3,
        suspiciousAccountActivity: true,
        shippingDetailsUsage: {
          initialUsageDate: "2014-01-26",
          initialUsageRange: "CURRENT_TRANSACTION",
          cardHolderNameMatch: true
        },
        paymentAccountDetails: {
          createdDate: "2014-01-26",
          createdRange: "NO_ACCOUNT"
        },
        userLogin: {
          data: "Some up to 2048 bytes undefined data",
          authenticationMethod: "NO_LOGIN",
          time: "2014-01-26T10:32:28Z"
        },
        travelDetails: {
          departureDate: "2014-01-26",
          passengerFirstName: "John",
          passengerLastName: "Smith",
          origin: "BCN",
          destination: "SOF",
          airlineCarrier: "Wizz air",
          isAirTravel: true
        },
        priorThreeDSAuthentication: {
          data: "Some up to 2048 bytes undefined data",
          method: "FRICTIONLESS_AUTHENTICATION",
          time: "2014-01-26T10:32:28Z"
        }
      }
    }
  };
  instance
    .tokenize(tokenizationOptions)
    .then((result) => {
      $form
        .find(".pay")
        .html('Processing <i class="fa fa-spinner fa-pulse"></i>');
      /* Hide Paysafe errors on the form */
      $form.find(".payment-errors").closest(".row").hide();
      $form.find(".payment-errors").text("");

      // response contains token
      console.log("Tokenization resolved.");
      console.log(result);

      // you would send the 'token' to your server here using AJAX. The delay function simulates this process.
      console.log("POST https://api.test.paysafe.com/paymenthub/v1/payments");
      console.log("Payload for payments:");
      // We can send the payload directly to the Payments API
      console.log(
        JSON.stringify({
          merchantRefNum: tokenizationOptions.merchantRefNum,
          amount: tokenizationOptions.amount,
          currencyCode: options.currencyCode,
          paymentHandleToken: result.token,
          description: "Demo Card Payment Paysafe Js"
        })
      );
      $form.find(".pay").html('Payment successful <i class="fa fa-check"></i>');
      $form.find(".pay").prop("disabled", true);
    })
    .catch((error) => {
      console.log("Error on tokenization.");
      console.log(error);
      $form.find(".pay").html("Try again").prop("disabled", false);
      /* Show Paysafe errors on the form */
      $form.find(".payment-errors").text(error.displayMessage);
      $form.find(".payment-errors").closest(".row").show();
    });
}

function addEventListeners() {
  instance
    .fields("cvv cardNumber expiryDate")
    .valid(function (eventInstance, event) {
      $(event.target.containerElement)
        .closest(".form-control")
        .removeClass("error")
        .addClass("success");

      if (paymentFormReady()) {
        $form.find(".pay").prop("disabled", false);
      }
    });

  instance
    .fields("cvv cardNumber expiryDate")
    .invalid(function (eventInstance, event) {
      $(event.target.containerElement)
        .closest(".form-control")
        .removeClass("success")
        .addClass("error");
      if (!paymentFormReady()) {
        $form.find(".pay").prop("disabled", true);
      }
    });

  instance.fields.cardNumber.on("FieldValueChange", function (instance, event) {
    console.log(instance.fields.cardNumber);

    if (!instance.fields.cardNumber.isEmpty()) {
      var cardBrand = instance.getCardBrand().replace(/\s+/g, "");
      console.log(cardBrand);

      switch (cardBrand) {
        case "AmericanExpress":
          $form
            .find($(".fa"))
            .removeClass("fa-credit-card")
            .addClass("fa-cc-amex");
          break;
        case "MasterCard":
          $form
            .find($(".fa"))
            .removeClass("fa-credit-card")
            .addClass("fa-cc-mastercard");
          break;
        case "Visa":
          $form
            .find($(".fa"))
            .removeClass("fa-credit-card")
            .addClass("fa-cc-visa");
          break;
        case "Diners":
          $form
            .find($(".fa"))
            .removeClass("fa-credit-card")
            .addClass("fa-cc-diners-club");
          break;
        case "JCB":
          $form
            .find($(".fa"))
            .removeClass("fa-credit-card")
            .addClass("fa-cc-jcb");
          break;
        case "Maestro":
          $form
            .find($(".fa"))
            .removeClass("fa-credit-card")
            .addClass("fa-cc-discover");
          break;
      }
    } else {
      $form.find($(".fa")).removeClass().addClass("fa fa-credit-card");
    }
  });
}

function paymentFormReady() {
  if (
    $form.find("#cardNumber").hasClass("success") &&
    $form.find("#cardExpiry").hasClass("success") &&
    $form.find("#cardCVC").hasClass("success")
  ) {
    return true;
  } else {
    return false;
  }
}

function generateGuid() {
  return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) =>
    (
      c ^
      (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
    ).toString(16)
  );
}

              
            
!
999px

Console