NAV Navbar
Logo

payplug.js

If you do not want to redirect your customers to PayPlug’s hosted payment page, you can use payplug.js to securely display the payment form inside your website.

payplug.js

payplug.js encrypts credit card details in the browser and enables you to fully control the user experience without receiving sensitive card data on your server.

The library also provides powerful validators to check the credit card numer format, expiration date, type and CVV number.

payplug.js

  1. Include set-up elements (Js and publishable key)
  2. Create a payment token using payplug.js
  3. Post the token to your server
  4. Create a payment with the API

If you don’t have the time to read the full documentation and if you are really in a hurry to get started, you can go straight to our full example.

Security

If you want to host your own payment page on your website, you must address the following security basics.

Use TLS

Always ensure that all the traffic between your server and your customer browser is encrypted.

We do not support the SSL protocol because it is insecure, and recommend you deactivate SSLv3 from your server. Use TLS v1.1 or v1.2 instead. Finally, we recommand you use HTTPS to serve your web pages.

If you want to test the security of your website, you can use the following tools:

  1. Qualys SSL Server Test, a minimum rate of B is highly recommanded.
  2. Symantec CryptoReport.
  3. SSL Decoder.

PCI DSS

To host your own payment page, your website must comply with PCI DSS. You must complete the PCI DSS Self-Assessment Questionnaire (SAQ) to self evaluate your service to PCI compliance. You may need to share these details with PayPlug.

Useful Resources

Here is a small list of very useful articles about server security:

  1. Mozilla Wiki - Security/Server Side TLS.
  2. Mozilla SSL Configuration Generator.
  3. OWASP - Top 10 2013-Top 10.
  4. SSL Certificate Installation Instructions & Tutorials.
  5. PCI SSC Data Security Standards Overview.

3-D Secure

3-D Secure is natively embedded in the payment page when using payplug.js. You do not have to implement any 3-D Secure handing in your integration.

When 3-D Secure is needed, payplug.js displays an overlay pop-up window embedding the 3-D Secure page within an iFrame. 3-D Secure parameter is set in the 3-D Secure configuration screen of the PayPlug Portal and it is not possible to force 3-D Secure for an individual payment within the API.

Include set-up elements

Including payplug.js

<script type="text/javascript" src="https://api.payplug.com/js/1.0/payplug.js"></script>

To use payplug.js add the opposite script tag in the page that will serve the payment form.

Setting your publishable key

Payplug.setPublishableKey('pk_live_7dfbd7213f2228142d96063b5f7a10db');

Before using payplug.js you must set your publishable key (available in your account) with setPublishableKey to communicate with PayPlug.

Handling errors

payplug.js indicates errors from the payment form (client side) and shows errors from the API (server side) when there is an issue after submitting the form.

This enables you to handle all error messages within the same script.

Client side error messages

Error example:

{
  "message":"Problem with publishable key. For more information see PayPlug Documentation (https://www.payplug.com/docs/api)",
  "name":"cvv_invalid"
}

payplug.js returns error messages, enabling you to display them directly in the browser.

Error messages format:

Key Description
message string A short human-readable description of the cause of the error.
name string Error message name.

Error messages:

Name Message
publishable_key_not_found The publishable key was not found, you need to use "Payplug.setPublishableKey()".
incorrect_publishable_key The publishable key was incorrect.
payplug_form_not_found Your form need to have an attribute: "data-payplug=’form’" in the field <form>.
card_number_not_found You need to have an input field with attribute: "data-payplug=’card_number’" in your form.
cvv_not_found You need to have an input field with attribute: "data-payplug=’card_cvv’" in your form.
expiry_date_not_found You need to have an input field with attribute: "data-payplug=’card_month_year’" in your form.
card_number_invalid The card number seems to be incorrect.
expiry_date_invalid The date seems to be incorrect, the format is (MM/YYYY).
cvv_invalid  The CVV was invalid.
encrypt_errors A problem occurred during encryption of card data.
payplug_api_error Error message sent by the API. All API error messages are described in the API Reference.

Client-side validation

Card number validation:

Payplug.card.validateCardNumber('4242 4242 4242 4242') // true
Payplug.card.validateCardNumber('4242-4242-4242-4242') // true
Payplug.card.validateCardNumber('4242424242424242')    // true
Payplug.card.validateCardNumber('5184-9200-0000-0097') // false
Payplug.card.validateCardNumber('this-is-a-card')      // false
Payplug.card.validateCardNumber('123456789')           // false

 Card expiration validation:

Payplug.card.validateExpiry('08/2020') // true
Payplug.card.validateExpiry('08/20')   // true
Payplug.card.validateExpiry('8/20')    // true
Payplug.card.validateExpiry('8/2020')  // true
Payplug.card.validateExpiry('08/10')   // false
Payplug.card.validateExpiry('08/2010') // false
Payplug.card.validateExpiry('08 2020') // false
Payplug.card.validateExpiry('08-2020') // false
Payplug.card.validateExpiry('2020/08') // false

CVV validation:

Payplug.card.validateCVV('123')  // true
Payplug.card.validateCVV('1234') // false
Payplug.card.validateCVV('12')   // false
Payplug.card.validateCVV('')     // false

Card type validation:

Payplug.card.cardType('4242424242424242') // visa
Payplug.card.cardType('5500005555555559') // mastercard
Payplug.card.cardType('5555222211111111') // null

payplug.js provides a client-side validation, which allows to check the validity of the payment card, the CVV, the card type and the card expiration.

Validation Description
Payplug.card.validateCardNumber Returns true or false Checks the number format and the Luhn algorithm. Compliance space or any other punctuation characters will be ignored.
Payplug.card.validateExpiry Returns true or false Checks if the expiration date is a date in the future.
Payplug.card.validateCVV Returns true or false Check if the CVV could be a valid verification code.
Payplug.card.cardType Returns visa, mastercard or null Checks the payment card number and return the type of the card.

Create a payment token

To create a payment page on your own website with payplug.js :

  1. create a simple payment form,
  2. paste a few lines of javascript in your page header.

Because your payment form is going to collect very sensitive data, payplug.js prevents them from being routed through your server by converting all sensitive data into an encrypted token. You can then use this token to create a payment with the PayPlug API.

Example:

var form = document.querySelectorAll("#signupForm")[0];
Payplug.card.createToken(form, payplugResponseHandler,
  {'amount': 1000,
    'currency': 'EUR',
    'card_number': '4242 4242 4242 4242',
    'card_cvv': 400,
    'card_month': 12,
    'card_year': 2019
  });

Simple example while using data-payplug attribute in your form:

var form = document.querySelectorAll("#signupForm")[0];
Payplug.card.createToken(form, payplugResponseHandler,
  {'amount': 1000,
    'currency': 'EUR'
  });

Form example using the data-payplug attributes:

<form action="" method="post" id="signupForm" class="form" novalidate data-payplug="form">
  <div class="input-error-wrapper" id="error-api">
    <p class="input-error" id="error-api-bad"></p>
  </div>
  <p>
    <input type="text" class="form-control" placeholder="First Name" name="firstname" value="" >
  </p>
  <p>
    <input type="text" class="form-control" placeholder="Last Name" name="lastname" value="" >
  </p>
  <p>
    <input type="text" placeholder="Email" name="email" value="" >
  </p>
  <p>
    <input type="text" placeholder="Card number" value="" data-payplug="card_number" >
  </p>
  <div class="input-error-wrapper" id="error-card">
    <p class="input-error" id="error-card-bad">Invalid payment card number.</p>
  </div>
  <p>
    <input type="text" placeholder="CVV" autocomplete="off" data-payplug="card_cvv">
  </p>
  <div class="input-error-wrapper" id="error-cvv">
    <p class="input-error" id="error-cvv-bad">Invalid CVV code.</p>
  </div>
  <p>
    <input type="text" placeholder="Expiration (MM/YYYY)" data-payplug="card_month_year">
  </p>
  <div class="input-error-wrapper" id="error-expiry">
    <p class="input-error" id="error-expiry-bad">Invalid credit card expiration date.</p>
  </div>
  <p>
    <button type="submit" data-payplug='submit'>Submit payment</button>
  </p>
</form>

Use the createToken function to create a single-use payment token with the following parameters:

Parameters Description
amount positive integer required Amount of the payment in cents.
currency positive integer required Currency code (three-letter ISO 4217) in which the payment was made.
card_number string optional Credit card number.
card_cvv integer optional Credit card CVV.
card_month integer optional Credit card expiration month.
card_year integer optional Credit card expiration year.

As an alternative, you can also assign the required parameters to the data-payplug attribute into your form input fields instead of passing the attributes directly in the createToken function.

If you do not already have your customer e-mail address, do not forget to add an e-mail field in your form, as you will have to provide one to process a payment with the PayPlug API.

To be sure the data are not routed through your server when submitting the form, do not add name attributes in any input fields.

Post the token to your server

var payplugResponseHandler = function(code, response, details) {
  console.log(code + ' : ' + response + ' : ' + details);
  if (code == 'card_number_invalid') {
    document.querySelectorAll("#error-card-bad")[0].style.display = 'block';
  }
  if (code == 'cvv_invalid') {
    document.querySelectorAll("#error-cvv-bad")[0].style.display = 'block';
  }
  if (code == 'expiry_date_invalid') {
    document.querySelectorAll("#error-expiry-bad")[0].style.display = 'block';
  }
  if (code == 'payplug_api_error') {
    document.querySelectorAll("#error-api-bad")[0].innerHTML = response + ', details: ' +  details;
    document.querySelectorAll("#error-api-bad")[0].style.display = 'block';
  }
  return false;
};

The call payplugResponseHandler handles the response from the API and the payment submission, including any errors that may occur.

If the card information is correct, it will return a single-use payment token to the form in Payplug.card.createToken.

The data from the form is then sent as an HTTP POST to your server, on the URL defined in the action attribute.

Submission to the API

<?php
$secretkey = "sk_test_9898098098guGYUG9";

// replace with your own variable
$firstname = htmlspecialchars($_POST['firstname']);
$lastname = htmlspecialchars($_POST['lastname']);
$email = htmlspecialchars($_POST['email']);
$token = $_POST['payplugToken'];

require_once("payplug_php/lib/init.php");
\Payplug\Payplug::setSecretKey($secretkey);

$payment = \Payplug\Payment::create(array(
  'amount'         => 1000,
  'currency'       => 'EUR',
  'payment_method' => $token,
  'customer'       => array(
      'email'        => $email,
      'first_name'   => $firstname,
      'last_name'    => $lastname
  ),
  'notification_url' => 'https://example.net/notifications'
));

Once the form is submitted, the payment card information can now be send to the PayPlug API in the payment_method attribute.

Example in different langage are available in the PayPlug API documentation.

Full example

Page index.html with the payment page based on Bootstrap:

<!DOCTYPE html>
<html lang="en">
<head>
<title>payplug.js example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="//netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.css" rel="stylesheet">
<script type="text/javascript" src="https://api.payplug.com/js/1.0/payplug.js"></script>
<script type="text/javascript">
  Payplug.setPublishableKey('pk_live_7dfbd7213f2228142d96063b5f7a10db');

  var payplugResponseHandler = function(code, response, details) {
    console.log(code + ' : ' + response + ' : ' + details);
    if (code == 'card_number_invalid') {
      document.querySelectorAll("#error-card-bad")[0].style.display = 'block';
    }
    if (code == 'cvv_invalid') {
      document.querySelectorAll("#error-cvv-bad")[0].style.display = 'block';
    }
    if (code == 'expiry_date_invalid') {
      document.querySelectorAll("#error-expiry-bad")[0].style.display = 'block';
    }
    if (code == 'payplug_api_error') {
      document.querySelectorAll("#error-api-bad")[0].innerHTML = response + ', details: ' +  details;
      document.querySelectorAll("#error-api-bad")[0].style.display = 'block';
    }
    return false;
  };

  document.addEventListener('DOMContentLoaded', function() {
    [].forEach.call(document.querySelectorAll("[data-payplug='form']"), function(el) {
      el.addEventListener('submit', function(event) {
          var form = document.querySelectorAll("#signupForm")[0];
          Payplug.card.createToken(form, payplugResponseHandler,
            {'amount': 800,
            'currency': 'EUR'
            });
          event.preventDefault();
      })
    })
  })
</script>
</head>
<body>
  <div class="container">
    <div class="row">
      <div class='col-md-12'>
        <h1><i class="fa fa-flask"></i> payplug.js example</h1>
        <hr />
        <p>Welcome,</p>
        <p>This example is creating a payment of 8€.</p>
      </div>
      <div class='col-md-4'>
      <form action="payment.php" method="POST" id="signupForm" class="form" novalidate data-payplug="form">
        <div class="input-error-wrapper" id="error-api">
          <p class="input-error" id="error-api-bad"></p>
        </div>
        <p>
          <input type="text" class="form-control" placeholder="First Name" name="firstname" value="" >
        </p>
        <p>
          <input type="text" class="form-control" placeholder="Last Name" name="lastname" value="" >
        </p>
        <p>
          <input type="text" class="form-control" placeholder="Email" name="email" value="" >
        </p>
        <p>
          <input type="text" class="form-control" placeholder="Card number" value="" data-payplug="card_number" >
        </p>
        <div class="input-error-wrapper" id="error-card">
          <p class="input-error" id="error-card-bad" style="display:none;">Invalid payment card number.</p>
        </div>
        <p>
          <input type="text" class="form-control" placeholder="CVV" autocomplete="off" data-payplug="card_cvv">
        </p>
        <div class="input-error-wrapper" id="error-cvv">
          <p class="input-error" id="error-cvv-bad" style="display:none;">Invalid CVV code.</p>
        </div>
        <p>
          <input type="text" class="form-control" placeholder="Expiration (MM/YY)" data-payplug="card_month_year">
        </p>
        <div class="input-error-wrapper" id="error-expiry">
          <p class="input-error" id="error-expiry-bad" style="display:none;">Invalid credit card expiration date.</p>
        </div>
        <p>
          <button type="submit" class="btn btn-default" data-payplug='submit'>Submit payment</button>
        </p>
      </form>
      </div>
    </div>
  </div>
</body>
</html>

Page payment.php to create the payment:

<?php
$secretkey = "sk_test_9898098098guGYUG9";

$firstname = htmlspecialchars($_POST['firstname']);
$lastname = htmlspecialchars($_POST['lastname']);
$email = htmlspecialchars($_POST['email']);
$token = $_POST['payplugToken'];

require_once("payplug-php/lib/init.php");
\Payplug\Payplug::setSecretKey($secretkey);

try {
  $payment = \Payplug\Payment::create(array(
    'amount'         => 800,
    'currency'       => 'EUR',
    'payment_method' => $token,
    'customer'       => array(
      'email'        => $email,
      'first_name'   => $firstname,
      'last_name'    => $lastname
    ),
    'notification_url' => 'https://example.net/notifications'
  ));
} catch (\Payplug\Exception\ConnectionException $e) {
  echo "Connection  with the PayPlug API failed.";
} catch (\Payplug\Exception\InvalidPaymentException $e) {
  echo "Payment object provided is invalid.";
} catch (\Payplug\Exception\UndefinedAttributeException $e) {
  echo "Requested attribute is undefined.";
} catch (\Payplug\Exception\HttpException $e) {
  echo "Http errors.";
} catch (\Payplug\Exception\PayplugException $e) {
  echo 'Failure code: ' . $e->getMessage();
} catch (Exception $e) {
  echo 'Caught exception: '. $e->getMessage();
}

if ($payment->is_paid == true) {
  echo "<div><strong>Thanks " . $payment->customer->email . ", your payment has been accepted.</strong></div>";
} else {
  var_dump($e); 
  echo "<div><strong>Error !</strong><br />". $payment->failure->message ." (" . $payment->failure->code . ").</div>";
}

Try this example to see all the elements described in this documentation working together.

The example is divided in 2 pages, one page with the payment form and one page in which the payment information is posted and then process the payment using the PayPlug API.