Sale using L2 and L3

This example makes a sale with the payment iFrame and sends Level 2 and Level 3 order data in the same submitPayment() call. Commercial and purchasing cards that receive this data can qualify for lower interchange rates.

This example points at the sandbox gateway. Replace __LOCATION_ID__ and __API_KEY__ with your sandbox values before running it.

Keep the API key on your server

fetchAccessToken() is here for demo purposes only. In production your server requests the access token and passes only the token to the page.

How it works

  1. The page requests an access token for the location.
  2. It loads the SoftPoint Pay script and calls initPaymentForm() to render the card fields in iframeContent.
  3. When the customer presses Pay With Credit Card, the page calls submitPayment() with the sale details plus the Level 2 and Level 3 fields.
  4. The iFrame returns the result to onApprovedCallback, onDeclinedCallback or onErrorCallback.

Example

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Sale with Level 2 / Level 3 Data - Sandbox</title>
  <link rel="stylesheet" type="text/css"
        href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

  <style>
    @import url("https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800&display=swap");
    body {
      font-family: "Poppins", sans-serif;
      font-weight: 300;
    }

    .card-header {
      padding: .5rem 1rem;
      margin-bottom: 0;
      background-color: rgba(0, 0, 0, .03);
      border-bottom: none;
    }

    .btn-light:focus {
      color: #212529;
      background-color: #e2e6ea;
      border-color: #dae0e5;
      box-shadow: 0 0 0 0.2rem rgba(216, 217, 219, .5);
    }

    .free-button {
      background: #1565c0;
      height: 52px;
      font-size: 15px;
      border-radius: 8px;
    }
  </style>
</head>

<body>
<div id="containerIframe" class="d-flex justify-content-center align-items-start p-4">
  <!-- You can specify the width here -->
  <div style="width: 468px; max-width: 100%;">
    <span>Payment Method - Sale (Level 2 / Level 3)</span>
    <div class="card">
      <div class="accordion" id="accordionExample">
        <div class="card">
          <div class="card-header p-0">
            <h2 class="mb-0">
              <button style="width: 100%" class="btn btn-light btn-block text-left p-3 rounded-0"
                      data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                <div class="d-flex align-items-center justify-content-between">
                  <span>Credit card</span>
                </div>
              </button>
            </h2>
          </div>
          <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordionExample">
            <form>
              <div id="iframeContent"></div>
              <div
                      style="padding-left: 1rem !important; padding-right: 1rem !important; padding-bottom: 1rem !important;">
                <button id="myPayButton" type="submit" class="btn btn-block free-button"
                        style="background-color: #dd051f; color: white" disabled>
                  Pay With Credit Card
                </button>
              </div>
              <p style="text-align:center; word-break: break-word;" id="response"></p>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<script>
  // Replace with your sandbox values.
  const locationId = __LOCATION_ID__;
  const apiKey = '__API_KEY__';

  const GATEWAY_URL = 'https://api-gtw.softpoint.io';
  const IFRAME_URL = 'https://iframe-gtw.softpoint.io';

  let accessToken = '';
  let sessionID = '';

  /*
      Level 2 / Level 3 order data.

      Level 2: tax_amount, purchase/order references, customer account, buyer tax id.
      Level 3: freight, duty, discount, shipping address and one line per product in order.items.

      The card is charged `amount`. Keep it equal to:
        sum(items.total_amount) + tax_amount + freight_amount + duty_amount - discount_amount
      orderTotal() below calculates it from the lines so the two always match.
  */
  const orderId = 'INV-' + Date.now();

  const order = {
    tax_amount: 32.38,          // L2: total sales tax on the order
    discount_amount: 10.00,     // L3: order-level discount
    freight_amount: 15.00,      // L3: shipping
    duty_amount: 0.00,          // L3: import duty
    tax_status: 'taxable',      // 'taxable' or 'exempt'
    summary_commodity_code: '5610',
    buyer_tax_id: '123456789',  // buyer EIN; omit the key when there is none
    customer_account_number: 'CUST-00042',
    shipping_address: {
      name: 'Acme Logistics LLC',
      first_name: 'Test',
      last_name: 'User',
      email: '[email protected]',
      phone: '3105550100',
      street: '1200 Pine Dr Suite 300',
      city: 'Los Angeles',
      state: 'CA',
      zip: '90001',
      country_iso: 'US',
    },
    items: [
      lineItem({
        name: 'Ergonomic Office Chair', sku: 'CHR-100', product_code: 'CHR100',
        quantity: 2, unit_price: 125.00, tax_amount: 21.88,
        uom: 'EA', commodity_code: '56101504', sales_category: 'Furniture',
      }),
      lineItem({
        name: 'Printer Paper, Case', sku: 'PPR-500', product_code: 'PPR500',
        quantity: 3, unit_price: 40.00, tax_amount: 10.50,
        uom: 'CS', commodity_code: '14111507', sales_category: 'Office Supplies',
      }),
    ],
  };

  // One Level 3 line item.
  function lineItem(p) {
    const total = round2(p.quantity * p.unit_price);
    return {
      name: p.name,
      product_name: p.name,
      product_code: p.product_code,
      sku: p.sku,
      quantity: p.quantity,
      price: total,                 // gateway rule: must be greater than 0
      unit_price: p.unit_price,
      total_amount: total,
      tax: p.tax_amount,
      tax_amount: p.tax_amount,
      tax_status: p.tax_amount > 0 ? 'taxable' : 'exempt',
      discount_amount: 0,
      amount_includes_tax: false,
      uom: p.uom,                   // unit of measure: EA, CS, LB, ...
      commodity_code: p.commodity_code, // UNSPSC
      sales_category: p.sales_category,
      invoice_number: orderId,
    };
  }

  function round2(n) {
    return Math.round(n * 100) / 100;
  }

  function orderTotal() {
    const items = order.items.reduce((sum, i) => sum + i.total_amount, 0);
    return round2(items + order.tax_amount + order.freight_amount + order.duty_amount - order.discount_amount);
  }

  /*
      fetchAccessToken function is for demo purposes only.
      Credentials must not be exposed in the front end: in production your server
      requests the access token and passes only the token to the page.
  */
  async function fetchAccessToken() {
    const url = GATEWAY_URL + '/api/locations/' + locationId + '/access_token';

    const requestOptions = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Api-Key': apiKey,
      },
    };

    try {
      const response = await fetch(url, requestOptions);
      const data = await response.json();
      if (!data.accessToken) {
        showResponse('access_token failed (HTTP ' + response.status + '): ' + JSON.stringify(data.error || data), 'red');
        return null;
      }
      return data.accessToken;
    } catch (error) {
      console.error('Error:', error);
      showResponse('access_token request failed: ' + error.message, 'red');
      return null;
    }
  }

  async function loadAndProcessOrderWithAccessToken() {
    accessToken = await fetchAccessToken();
    if (!accessToken) {
      return;
    }

    const scriptElement = document.createElement('script');
    scriptElement.src = IFRAME_URL + '/api/softpoint-pay?location_id=' + locationId + '&session_key=' + encodeURIComponent(accessToken);
    document.head.appendChild(scriptElement);

    // Fraud screening (ThreatMetrix) session for the card form.
    const orgID = 'rpzdrvix';
    const merchantID = '20022141';
    sessionID = generateUUID();
    const tmScript = document.createElement('script');
    tmScript.src = `https://h.online-metrix.net/fp/tags.js?org_id=${orgID}&session_id=${merchantID}${sessionID}`;
    tmScript.type = 'text/javascript';
    document.head.appendChild(tmScript);

    scriptElement.onload = function () {
      const conf = {
        "location_id": locationId,
        "access_token": accessToken,
        "process_type": "sale",
        "payment_methods": ["credit_card"],
        "include-cardholder": 1,
        "amount": orderTotal().toFixed(2),
        "currency_iso": "USD",
        "user_id": '5000',
        "country_iso": "US",
      };

      initPaymentForm('iframeContent', conf);
    };
  }

  loadAndProcessOrderWithAccessToken();

  const form = document.querySelector('form');
  form.addEventListener('submit', (event) => {
    event.preventDefault();
    document.getElementById('myPayButton').disabled = true;

    const paymentDetails = {
      session_id: sessionID,
      location_id: locationId,
      access_token: accessToken,
      process_type: 'sale',
      amount: orderTotal().toFixed(2),
      currency_iso: 'USD',
      user_id: '5000',
      country_iso: 'US',
      email: order.shipping_address.email,
      phone_number: order.shipping_address.phone,
      storeCard: 0,

      // ----- Level 2 -----
      tax_amount: order.tax_amount,
      orderid: orderId,
      inv_number: orderId,
      purchase_order_number: orderId,
      customer_account_number: order.customer_account_number,
      tax_status: order.tax_status,
      buyer_tax_id: order.buyer_tax_id,

      // ----- Level 3 -----
      discount_amount: order.discount_amount,
      freight_amount: order.freight_amount,
      duty_amount: order.duty_amount,
      summary_commodity_code: order.summary_commodity_code,
      shipping_address: order.shipping_address,
      order: {
        items: order.items,
      },
    };

    console.log('submitPayment', paymentDetails);
    submitPayment(paymentDetails);
  });

  function onApprovedCallback(e) {
    console.log('onApprovedCallback called', e);
    showResponse(e, 'green');
    document.getElementById('myPayButton').disabled = false;
  }

  function onDeclinedCallback(e) {
    console.log('onDeclinedCallback called', e);
    if (e != 'input_error') {
      showResponse(e, 'red');
    }
    document.getElementById('myPayButton').disabled = false;
  }

  function onErrorCallback(e) {
    console.log('onErrorCallback called', e);
    document.getElementById('myPayButton').disabled = false;
  }

  // Called when the card carries a surcharge. Nothing is charged until confirmSurcharge() is called.
  function onSurchargeConfirmationRequired(e) {
    const ok = window.confirm('A card surcharge of $' + Number(e.surcharge_amount).toFixed(2)
      + ' applies. Total: $' + Number(e.total_amount).toFixed(2) + '. Proceed?');
    confirmSurcharge(ok);
  }

  // Enable Pay once the iframe reports it is ready.
  window.addEventListener('message', (event) => {
    if (event.origin !== new URL(IFRAME_URL).origin) return;
    if (event.data && event.data.type === 'iframeLoaded') {
      document.getElementById('myPayButton').removeAttribute('disabled');
    }
  });

  function showResponse(data, color) {
    const response = document.querySelector('#response');
    response.innerHTML = typeof data === 'string' ? data : JSON.stringify(data);
    response.style.color = color;
  }

  function generateUUID() {
    let d = new Date().getTime();
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      const r = (d + Math.random() * 16) % 16 | 0;
      d = Math.floor(d / 16);
      return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
  }
</script>
</body>

</html>

Level 2 fields

FieldTypeDescription
tax_amountnumberTotal sales tax on the order.
orderidstringYour order ID.
inv_numberstringInvoice number.
purchase_order_numberstringCustomer purchase order number.
customer_account_numberstringCustomer account or customer code.
tax_statusstringtaxable or exempt.
buyer_tax_idstringBuyer tax ID (EIN). Omit the field when there is none.

Level 3 fields

FieldTypeDescription
discount_amountnumberOrder-level discount.
freight_amountnumberShipping charge.
duty_amountnumberImport duty.
summary_commodity_codestringCommodity code that best describes the whole order.
shipping_addressobjectShip-to details: name, first_name, last_name, email, phone, street, city, state, zip, country_iso.
order.itemsarrayOne entry per product. See the table below.

Line item fields (order.items[])

FieldTypeDescription
namestringItem description.
product_namestringProduct name.
product_codestringYour product code.
skustringItem SKU.
quantitynumberUnits sold.
unit_pricenumberPrice of one unit.
pricenumberLine amount. Must be greater than 0.
total_amountnumberLine total (quantity × unit_price).
taxnumberTax on the line.
tax_amountnumberTax on the line.
tax_statusstringtaxable or exempt.
discount_amountnumberDiscount on the line.
amount_includes_taxbooleantrue if total_amount already includes tax.
uomstringUnit of measure, for example EA (each) or CS (case).
commodity_codestringUNSPSC commodity code for the item.
sales_categorystringCategory of the item.
invoice_numberstringInvoice the line belongs to.
❗️

Amount must match the order

amount must equal the sum of the line total_amount values, plus tax_amount, freight_amount and duty_amount, minus discount_amount. The example calculates it with orderTotal(). A line with a price of 0.00 is rejected by the gateway.

Response Fields

FieldTypeDescription
amount_approvedstringAmount approved.
servicefee_amountnumberService fee charged.
surcharge_amountnumberCard surcharge charged.
tip_amount_approvednumberTip approved.
conveniencefee_amountnumberConvenience fee charged.
order_idstringOrder ID.
authcodestringAuthorization code.
reference_idstringReference ID.
currency_isostringCurrency code.
transaction_idstringSoftPoint transaction ID.
card_dataobjectCard details.
card_data.cardfullnamestringCardholder name.
card_data.expiry_informationstringCard expiry.
card_data.last4stringLast four digits of the card.
card_data.card_brandstringCard brand.
approvalCodestringApproval code from the processor.
networkTransactionIdstringCard network transaction ID.
inv_numberstringInvoice number sent with the sale.
networkReconciliationIdstringNetwork reconciliation ID.
avsCodestringAddress verification result.
avsCodeRawstringRaw address verification code from the processor.
cardVerificationstringCard verification (CVV) result.
cardVerificationRawstringRaw card verification code from the processor.
transaction_nostringTransaction number.

Response Example

{
  "amount_approved": 407.38,
  "servicefee_amount": 0,
  "surcharge_amount": 0,
  "tip_amount_approved": 0,
  "conveniencefee_amount": 0,
  "order_id": "INV-1763592000000",
  "authcode": "A0000",
  "reference_id": "__REFERENCE_ID__",
  "currency_iso": "USD",
  "transaction_id": "__TRANSACTION_ID__",
  "card_data": {
    "cardfullname": "Test User",
    "expiry_information": "4/33",
    "last4": "3713",
    "card_brand": "Visa"
  },
  "approvalCode": "A0000",
  "networkTransactionId": "",
  "inv_number": "INV-1763592000000",
  "networkReconciliationId": "",
  "avsCode": "",
  "avsCodeRaw": "",
  "cardVerification": "N",
  "cardVerificationRaw": "N",
  "transaction_no": "__TRANSACTION_NO__"
}

What’s Next

Did this page help you?