Applepay Tokenization

How it work?

Apple Pay is simple to set up. Just add your credit or debit card to the Wallet app on your iPhone and you're ready to go.

Requirements

  • Wallet with credit cards ... show the link that explains how to set up a wallet with the sandbox cards.
  • All pages that include Apple Pay must be served over HTTPS
  • Your domain must have a valid SSL certificate
  • your server must support Transport Layer Security (TLS). protocol version 1.2 or later
  • The Apple Pay APIs are available in Safari on the following platforms (Worldwide except for China):
  • Follow the next instructions to use Apple Pay in sandbox mode: Create a Sandbox Tester Account

Environment setup

Enable the domain

  1. Contact Jupiter support to share the domains where apple pay will be used.
  2. Copy the well-know file content

Apple Pay configuration

JupiterHq uses the official Apple Pay software development kit. In the following example, you can see a sample configuration.

<html>
  <head>
    <title>apple-pay-js-stubs Example</title>
    <!-- Official Apple Pay SDK CDN -->
    <script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script>
    <!-- jQuery for DOM manipulation -->
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    <!-- Axios for https request -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
      apple-pay-button {
        --apple-pay-button-width: 150px;
        --apple-pay-button-height: 30px;
        --apple-pay-button-border-radius: 3px;
        --apple-pay-button-padding: 0px 0px;
        --apple-pay-button-box-sizing: border-box;
      }
    </style>
  </head>

  <body>
    <h1>JupiterHQ Apple Pay implementation</h1>

    <h3>Transaction parameters form</h3>
    <form>
      <label for="description">Description</label><br />
      <input type="text" id="description" value="test transaction" required /><br />
      <br />
      <label for="amount">Amount</label><br />
      <input type="text" id="amount" value="3.00" required /><br />
    </form>

    <!-- Apple pay button instantiation -->
    <apple-pay-button id="payAction" buttonstyle="black" type="plain" locale="en"></apple-pay-button>
    <!-- See the next link for more examples of Buttons and marks -->
    <!-- https://developer.apple.com/design/human-interface-guidelines/apple-pay/overview/buttons-and-marks/  -->


    <script>
      $(document).ready(function () {
        // Simple amount field validation
        $('#amount').change(function () {
          if (!this.value) {
            $('#payAction').hide();
            alert('Please enter a valid amount');
          } else {
            $('#payAction').show();
          }
        });

        /**
         * ApplePaySession must be created from a user gesture handler.
         * https://developer.apple.com/documentation/apple_pay_on_the_web/apple_pay_js_api/creating_an_apple_pay_session
         * 
         * 
         * Implementing the function in the apple-pay-button.
        */
        $('#payAction').bind('click', function () {
          if (!ApplePaySession) {
            return;
          }
          /**
           * ApplePaySession is accessible only in supported browsers.
           * See the next link for more information
           * https://developer.apple.com/documentation/apple_pay_on_the_web
           */



          // Getting the values from the form to define the transaction values
          var TRANSACTION_DESCRIPTION = document.getElementById('description').value;
          var TRANSACTION_AMOUNT = document.getElementById('amount').value;


          // Complete with your JupiterHq subMerchant ID 
          const YOUR_SUBMERCHANT_ID = '874767775';
          /**
           * ------- CALLBACK EXAMPLE --------
           * @async
           * @method
           * @param {string} YOUR_SUBMERCHANT_ID - Your merchant ID
           * @param {string} TOKEN - Credit card token returned from Apple Pay
           * @param {string} AMOUNT - Transaction amount
           * @returns {Boolean} - Boolean success or failure
           * @throws {Error} - Error object
           *
           * @description - In the following example we are going to make a call that simulates
           * the request from your front end, to your backend endpoint, which will send the sales
           * transaction data to Jupiter services. You can use this as a reference to implement
           * your logic for transaction creations.
           */
          const executeOperation = async (YOUR_SUBMERCHANT_ID, TOKEN, AMOUNT) => {
            try {
              const saleTxResponse = await axios.post(`/applepay/saletransaction`, {
                subMerchantId: YOUR_SUBMERCHANT_ID,
                token: TOKEN,
                amount: AMOUNT,
                cardHolderInitiated: true,
              });
              console.log({ saleTxResponse });
              return true;
            } catch {
              return false;
            }
          };

          // THE FOLLOWING CODE MUST NOT BE MODIFIED FOR THE EXAMMPLE WORK SUCCESFULLY.
          const env = {
            dev: 'dev-platform.jupiterhq.com',
            sandbox: 'sandbox-platform.jupiterhq.com',
            prod: 'platform.jupiterhq.com',
          };

          const SESSION_TOKEN_ENDPOINT = (ENV = 'local') => `${ENV}/v1/transactions/creditcard/tokenization/${YOUR_SUBMERCHANT_ID}/session`;
          const VALIDATE_SESSION_ENDPOINT = (ENV = 'local') =>
            `${ENV}/v1/transactions/creditcard/tokenization/${YOUR_SUBMERCHANT_ID}/applepay/validatesession`;
          const TOKENIZE_ENDPOINT = (ENV = 'local') =>
            `${ENV}/v1/transactions/creditcard/tokenization/${YOUR_SUBMERCHANT_ID}/applepay/gettoken`;

          const applePaySessionParams = {
            countryCode: 'US', // const
            currencyCode: 'USD', // const
            merchantCapabilities: ['supports3DS'], // const
            supportedNetworks: ['visa', 'masterCard', 'amex', 'discover'], // const
            total: {
              label: TRANSACTION_DESCRIPTION,
              type: 'final', // const
              amount: TRANSACTION_AMOUNT,
            },
          };

          const session = new ApplePaySession(3, applePaySessionParams);

          session.onvalidatemerchant = async (event) => {
            console.log('session.onvalidatemerchant()');
            const appleUrl = event.validationURL;
            const clientUrl = window.location.hostname;

            const validateSessionResponse = await axios.post(
              VALIDATE_SESSION_ENDPOINT(env.local),
              { appleUrl, clientUrl, YOUR_SUBMERCHANT_ID },
              { headers: { 'Access-Control-Allow-Origin': '*' } }
            );
            session.completeMerchantValidation(validateSessionResponse.data);
          };

          session.onpaymentmethodselected = (event) => {
            console.log('session.onpaymentmethodselected()');
            console.log({ onpaymentmethodselected: event });
            // Define ApplePayPaymentMethodUpdate based on the selected payment method.
            // No updates or errors are needed, pass an empty object.
            const update = {
              newTotal: {
                label: TRANSACTION_DESCRIPTION,
                type: 'final',
                amount: TRANSACTION_AMOUNT,
              },
            };
            session.completePaymentMethodSelection(update);
          };

          session.onpaymentauthorized = async (event) => {
            console.log('session.onpaymentauthorized()');
            console.log({ onpaymentauthorized: event });
            const paymentAuthorization = event.payment;

            try {
              const sessionTokenResponse = await axios.get(SESSION_TOKEN_ENDPOINT(env.local), { YOUR_SUBMERCHANT_ID });
              const { sessionId } = sessionTokenResponse.data.data;
              const tokenResponse = await axios.post(
                TOKENIZE_ENDPOINT(env.local),
                { paymentAuthorization, sessionId, YOUR_SUBMERCHANT_ID },
                { headers: { 'Access-Control-Allow-Origin': '*' } }
              );
              const { token } = tokenResponse.data.data.data;
              const operationResult = await executeOperation(YOUR_SUBMERCHANT_ID, token, TRANSACTION_AMOUNT);
              const result = operationResult ? { status: ApplePaySession.STATUS_SUCCESS } : { status: ApplePaySession.STATUS_FAILURE };

              session.completePayment(result);
            } catch (error) {
              console.log(error);
            }
          };

          session.oncancel = (event) => {
            console.log({ oncancel: event });
            // Payment cancelled by WebKit
          };

          session.begin();
        });
      });
    </script>
  </body>
</html>

Code example

Only in SAFARI, you may enter the interactive demo below to check out ApplePay in action, to learn about the flow, style customization, and error handling.

Applepay Interactive Demo

Was this page helpful?

Search our blog, contact support. You can also chat live with other developers.

Search Results