@moyasar/moyasar-payment-form
TypeScript icon, indicating that this package has built-in type declarations

2.0.1 • Public • Published

Moyasar Payment Form

Usage

Sample Usage:

<!-- We must provide an empty element that moyasar form will be mounted into -->
<div class="mysr-form"></div>

<script>
  Moyasar.init({
      // Root must be an Element or a string with a valid CSS selector to an element
      element: '.mysr-form',

      // Set the form language
      // Default: <taken from current page>, falls back to en
      language: 'ar',

      // Provide additional translations
      // Default: en and ar
      translations: [
          'de': {
              // This is just a sample
              // Checkout resources/lang/en.json for the full list
              'error.authentication_error': 'Authentifizierungsfehler, Dienst ist jetzt nicht verfügbar'
          }
      ],

      // Set predefined option to ApplePay and card pay buttons, defaults to pay
      payment_button_type: 'buy'

      // Amount to pay in smallest currency unit (minor)
      amount: 100,

      // Currency
      currency: 'SAR',

      // Country (Needed for Apple Pay to function)
      country: 'SA',

      // Description of the payment
      description: 'Testing Moyasar payment form',

      // Publishable API key
      publishable_api_key: 'pk_live_some-random-string',

      // Supported networks (Used to display icons in payment form, and to accept only supported networks in Apple Pay)
      // default: ['mada', 'visa', 'mastercard']
      supported_networks: [
          'mada',
          'visa',
          'mastercard',
          'amex',
      ],

      // Form payment methods, default: ['creditcard', 'applepay', 'stcpay']
      payment_methods: [
          'creditcard',
          'applepay',
          'stcpay'
      ],

      // Optional: Used for doing any job before payment is submitted, can also cancel payment
      before_payment_callback: function (proceed, abort) {
          if (1 > 2) {
              proceed();
          } else {
              abort();
          }
      },

      // When a payment is initiated, the library will use this handler
      // Types:
      //        1 - string, a URL that will recieve the payment object (HTTP method: POST)
      //        2 - function, will be called with the payment object as an argument
      on_payment_init: '/checkout/payments/initiated',

      // When a payment is completed (either failed or succeeded), the library will use this handler
      // Types:
      //        1 - string, a URL that will recieve the payment object (HTTP method: POST)
      //        2 - function, will be called with the payment object as an argument
      on_payment_complete: '/checkout/payments/completed',

      // Moyasar's form callback URL, will be used to redirect the user when the payment has finished (Required)
      callback_url: 'https://my-store.xyz/checkout/payments/redirect',

      // Optional: can be used to control the redirection behaviour
      on_redirect: function (url) {

      },

      // Apple Pay Configurations (Required when ApplePay is enabled)
      apple_pay: {
          // Payment label
          label: 'My Store XYZ',

          // This endpoint must be implemented on the users backend
          // A JSON object will be posted to the URL (HTTP method: POST)
          // JSON: {validation_url: 'https://example.apple.com/validation/url'}
          // The server must use the given URL and make a POST request to it using
          // the merchant validation certificate (In SSL options)
          // The returned JSON object from Apple must be returned to the browser as is
          // with "Content-Type: application/json" header set in order for the library
          // to parse it
          validate_merchant_url: '/checkout/payments/apple-pay/validate-merchant',

          // Optional: Used to provide merchant capabilities for moyasar
          merchant_capabilities: [

          ],

          // Optional: Used to control Apple Pay JS version
          // Default: 6
          version: 9,

          // Optional: Used to handle authorization of payment
          // Args: payment object is passed from Apple to handler
          on_authorize: function (paymentObject) {
              // Manually handle auth (send it to Moyasar)
          }
      },

      // Optional, (used for development purposes only, please don't use it)
      base_url: 'https://api.moyasar.com',

      // Optional: Used to handle failures of the form
      on_failure: function (error) {

      }
  });
</script>

Configuration

Here is a list of acceptable configurations values for the form.

Element (element) [Required]

Element must be a valid CSS selector for the target element for form to be mounted in. Or can be an instance of DOM element Element. Here is an example:

element: '.payment-form', // Using a class
element: '#payment-form', // Using an ID
element: document.querySelector('.payment-form'), // or just providing an Element instance

Language (language) [Optional]

This option can be used to set display language for the form. If left empty, language will be inferred from <html> element then fallback to en if it cannot be inferred. Here is an example

language: 'en', // Displaying the form in English
language: 'ar', // Displaying the form in Arabic
language: 'fr', // Displaying the form in French (You need to provide your own translations)

Translations (translations) [Optional]

This option is used to add more translations to the form. Here is an example:

translations: {
    fr: {
        "validation.should_be_english_letters_only": "Le nom ne peut avoir que l'alphabet anglais et des espaces",
        "validation.first_and_last_name_required": "Le prénom et le nom de famille sont obligatoires",
    }
},

Payment Button Type (payment_button_type) [Optional]

This options allow to set predefined text for pay buttons - in card from and ApplePay (if configured).

payment_button_type: 'plain'; // Will display no additional text, only amount
payment_button_type: 'pay'; // Will display "Pay" label
payment_button_type: 'buy'; // Will display "Buy with" label
payment_button_type: 'donate'; // Will display "Donate with" label
payment_button_type: 'book'; // Will display "Book with" label
payment_button_type: 'check-out'; // Will display "Check out with" label
payment_button_type: 'subscribe'; // Will display "Subscribe with" label
payment_button_type: 'add-money'; // Will display "Add money with" label
payment_button_type: 'contribute'; // Will display "Contribute with" label
payment_button_type: 'order'; // Will display "Order with" label
payment_button_type: 'reload'; // Will display "Reload with" label
payment_button_type: 'rent'; // Will display "Rent with" label
payment_button_type: 'support'; // Will display "Support with" label
payment_button_type: 'tip'; // Will display "Tip with" label
payment_button_type: 'top-up'; // Will display "Top Up with" label
payment_button_type: 'continue'; // Will display "Continue with payment" label

Publishable API Key (publishable_api_key) [Required]

The publishable API key is required in order to communicate with Moyasar's API and complete the payment request. Here is an example:

You can get both keys from your account at Moyasar Dashboard

// Live key is used in production environemnt and will require a valid SSL certificate
publishable_api_key: 'pk_live_AQpxBV3a29qm392e4mkasjnRhzADVrxSq5ydVNui',

// This will put the form in testing mode and allow you to test without an SSL certificate
publishable_api_key: 'pk_test_AQpxBV3a29qm392e4mrT4Fawd3ADVrxSq5ydVNui',

Payment Methods (methods) [Optional]

This is used to enable and disable payment methods on the form. By default, all the methods are enabled, which are:

  • Credit Card (creditcard)
  • Apple Pay (applepay)
  • Stc Pay (stcpay)
// Enabling only Credit Card and Apple Pay
methods: ['creditcard', 'applepay'];

Amount (amount) [Required]

This sets the amount for user to pay. Amount must be in minor unit of selected currency, e.g. if we want to get a payment of $10 then we must represent the amount in Cents 1000. Here is an example:

amount: 1000;

Currency (currency) [Required]

This sets which currency is used for the amount to be paid. Here is an example:

currency: 'USD', // Get payment in US Dollars
currency: 'SAR', // Get payment in Saudi Riyals
currency: 'JPY', // Get Payment in Japanese Yen

The currency must be in ISO 3166-1 alpha-3 country code format.

Description (description) [Required]

This option is used to set a description to be sent along other payment information to Moyasar's API. Here is an example:

description: 'Payment for Order #34321';

The description can be any string you want.

Callback URL (callback_url) [Required]

This URL is used by Moyasar to redirect the user back after the payment is either successful, or the user has completed 3D stage.

Supported Networks (supported_networks) [Optional]

This optional configuration option is used to set accepted card networks in the form. The default value is all networks except amex.

Supported Networks:

  • Mada (mada)
  • Visa (visa)
  • Mastercard (mastercard)
  • American Express (amex)

Example:

supported_networks: [
    'mada',
    'visa',
    'mastercard',
    'amex'
],

Fixed Width (fixed_width) [Optional]

This option is used to limit the form width to only 360px and it is enabled by default. To disable this just set it to false.

Example:

fixed_width: false,

On Initiating (on_initiating) [Optional]

This Promise based callback is used to handle the event when a user starts a payment method and before any information is sent to Moyasar's API. You can use this to perform any last second validations or to prepare something.

When you handle this event, you can return a false to stop the payment process, or a dictionary that is either empty or contains description or callback_url values to update the form configurations if you need to.

Here is an example to stop the form from submitting:

on_initiating: async () => {
  return false;
};

Make the form proceed:

on_initiating: async function () {
    return {};
}

On Completed (on_completed) [Optional]

This event is fired when a payment is created by Moyasar's API. You can, intercept the payment to save it or do any other processing, by providing a Promise based callback;

Example:

on_completed: async function (payment) {
    // savePayment is just an example, your usage may vary.
    savePayment(payment)
}

On Failure (on_failure) [Optional]

This event is used to handle payment failure, you will get a string if there is an error.

Example:

on_failure: async (error) =>
  new Promise((resolve, reject) => {
    // Handle error
    resolve();
  });

On Redirect (on_redirect) [Optional]

When the form finishes it work and is about to redirect the user, you can intercept this action and handle redirection manually. Here is an example:

on_redirect: async (url) =>
  new Promise((resolve, reject) => {
    // Handle redirection manually
    resolve();
  });

Credit Card Configuration Options (credit_card)

This section describes Credit Card related options.

Manual (manual)

This option allows you to only authorize the payment without capturing it. You will need to capture the payment later using Moyasar API. Make a post POST to /v1/payments/{id}/capture.

Note: you need to enable this feature before using it.

credit_card: {
  manual: true;
}

Save Card (save_card)

This option allows you to tokenize the card while completing the transaction.

Note: you need to enable this feature before using it.

credit_card: {
  save_card: true;
}

Apple Pay Configurations (apple_pay) [Required if Apple Pay is activated]

This is an object that contains Apple Pay specific configurations. Here is an example:

apple_pay: {
  // Apple Pay Configurations
}

Version (version) [Optional]

This is used to specify Apple Pay JS version. Default is 6. Here is an example:

apple_pay: {
  version: 7;
}

Country (country) [Required]

Apple Pay merchant country. If other payment methods (Samsung Pay and/or Google Pay) are active, this can be set in payment_options.country to unify settings between multiple payments.

apple_pay: {
  country: 'SA';
}

or

payment_options: {
  country: 'SA';
}

Merchant Capabilities (merchant_capabilities) [Optional]

Merchant capabilities to activate for this Apple Pay session. Default is:

apple_pay: {
    merchant_capabilities: [
        'supports3DS',
        'supportsCredit',
        'supportsDebit'
    ],
},

Label (label) [Required]

Label to be displayed in the payment modal. If other payment methods (Samsung Pay and/or Google Pay) are active, this can be set in payment_options.label to unify settings between multiple payments. Here is an example:

apple_pay: {
  label: 'Ali Hardware Store';
}

or

payment_options: {
  label: 'Ali Hardware Store';
}

Merchant Validation URL (validate_merchant_url) [Optional]

This URL is used to initiate the Apple Pay session. A POST request will made to the specified endpoint with a JSON object containing the URL. Here is the JSON snippet:

{
  "validation_url": "https://url.to.applepay.tld/something/somthing"
}

The endpoint must return a response with the header Content-Type: application/json and the response return from Apple as is.

Here is the configuration example:

apple_pay: {
  validate_merchant_url: 'https://mystore.test/applepay/validate-merchant';
}

Supported Countries (supported_countries) [Optional]

An array of countries that cards are allowed from.

Default: ['SA']. Only Saudi Arabia is enabled by default to prevent fraudulent transactions, you may enable more countries at your own risk.

apple_pay: {
  supported_countries: ['SA', 'US'];
}

Google Pay Configurations (google_pay) [Required if Google Pay is activated]

This is an object that contains Google Pay specific configurations. Here is an example:

google_pay: {
  // Google Pay Configurations
}

Service ID (merchant_id) [Required]

This is used to specify Google Pay unique merchant ID:

google_pay: {
  merchant_id: 'dcc1cbb25d6a470bb42926';
}

Label (label) [Required]

Label to be displayed in the payment modal. If other payment methods (Samsung Pay and/or Apple Pay) are active, this can be set in payment_options.label to unify settings between multiple payments. Here is an example:

google_pay: {
  label: 'Ali Hardware Store';
}

or

payment_options: {
  label: 'Ali Hardware Store';
}

Country (country) [Required]

Google Pay merchant country. If other payment methods (Samsung Pay and/or Apple Pay) are active, this can be set in payment_options.country to unify settings between multiple payments.

google_pay: {
  country: 'SA';
}

or

payment_options: {
  country: 'SA';
}

Gateway Merchant ID (gateway_merchant_id) [Optional]

A optional string that can be used to provide ID provided by your merchant gateway.

google_pay: {
  gateway_merchant_id: 'YOUR_GATEWAY_MERCHANT_ID';
}

Environment (environment) [Optional]

A optional string that can be either TEST or PRODUCTION to manually define payment environment. Defaults value: PRODUCTION.

google_pay: {
  environment: 'TEST';
}

Samsung Pay Configurations (samsung_pay) [Required if Samsung Pay is activated]

This is an object that contains Samsung Pay specific configurations. Here is an example:

samsung_pay: {
  // Samsung Pay Configurations
}

Service ID (service_id) [Required]

This is used to specify Samsung Pay unique merchant ID:

samsung_pay: {
  service_id: 'dcc1cbb25d6a470bb42926';
}

Label (label) [Required]

Label to be displayed in the payment modal. If other payment methods (Apple Pay and/or Google Pay) are active, this can be set in payment_options.label to unify settings between multiple payments. Here is an example:

samsung_pay: {
  label: 'Ali Hardware Store';
}

or

payment_options: {
  label: 'Ali Hardware Store';
}

Country (country) [Required]

Samsung Pay merchant country. If other payment methods (Apple Pay and/or Google Pay) are active, this can be set in payment_options.country to unify settings between multiple payments.

samsung_pay: {
  country: 'SA';
}

or

payment_options: {
  country: 'SA';
}

Order Number (order_number) [Required]

Order number of the transaction.

samsung_pay: {
  order_number: 'DSTRF3457dsgTY';
}

Version (version) [Optional]

This is used to specify Samsung Pay version. Default is 2. Here is an example:

samsung_pay: {
  version: 2;
}

ID (id) [Optional]

This is the id value registered with Moyasar

samsung_pay: {
  id: 'idProvidedByPG';
}

Environment (environment) [Optional]

A optional string that can be either STAGE or PRODUCTION to manually define payment environment. Defaults value: PRODUCTION.

samsung_pay: {
  environment: 'STAGE';
}

Payment Options (payment_options) [Optional]

Optional object to share data between different payments methods.

payment_options: {
  label: 'Ali Hardware Store',
  country: 'SA',
}

Contribution

Please feel free to improve on this library by making a PR.

License

This software is licensed under the MIT license.

Readme

Keywords

none

Package Sidebar

Install

npm i @moyasar/moyasar-payment-form

Weekly Downloads

127

Version

2.0.1

License

MIT

Unpacked Size

1.15 MB

Total Files

12

Last publish

Collaborators

  • moyasar