Tutorial

Follow our tutorial to get a comprehensive understanding of Simplify Commerce.

Overview

It’s easy to use Simplify Commerce to integrate payments. You control the user experience, and all of the sensitive payments data is stored on our servers, making it much easier for you to be PCI compliant.

Due to the updated PCI standards, we recommend our hosted payments solution for integrating payments into your website.

If you are happy with hosting the payment form on your website and also conforming to the updated PCI standards, follow the steps below on what's needed to integrate payments.

Here's how it works:

How credit card processing works

Payments Form

In this tutorial you will learn how to collect credit card information, create a single-use token with that information, and send the token to your server.

Before we get started, let’s take a look at a typical payment form. Build this form in the way that you’re used to – with your web framework, or manually in HTML.

<form id="simplify-payment-form" action="" method="POST">
    <div>
        <label>Credit Card Number: </label>
        <input id="cc-number" type="text" maxlength="20" autocomplete="off" value="" autofocus />
    </div>
    <div>
        <label>CVC: </label>
        <input id="cc-cvc" type="text" maxlength="4" autocomplete="off" value=""/>
    </div>
    <div>
        <label>Expiry Date: </label>
        <select id="cc-exp-month">
            <option value="01">Jan</option>
            <option value="02">Feb</option>
            <option value="03">Mar</option>
            <option value="04">Apr</option>
            <option value="05">May</option>
            <option value="06">Jun</option>
            <option value="07">Jul</option>
            <option value="08">Aug</option>
            <option value="09">Sep</option>
            <option value="10">Oct</option>
            <option value="11">Nov</option>
            <option value="12">Dec</option>
        </select>
        <select id="cc-exp-year">
            <option value="13">2013</option>
            <option value="14">2014</option>
            <option value="15">2015</option>
            <option value="16">2016</option>
            <option value="17">2017</option>
            <option value="18">2018</option>
            <option value="19">2019</option>
            <option value="20">2020</option>
            <option value="21">2021</option>
            <option value="22">2022</option>
        </select>
    </div>
    <button id="process-payment-btn" type="submit">Process Payment</button>
</form>

See how the input fields for card data do not have a “name” attribute. This is done so the data is not stored on your server when the form is submitted.

This ensures you do not have to worry about data encryption of card holder data.

This is done through the simplify.js script. The script converts the cardholder data to a token which is simple, safe, and secure. Now you safely charge your customers using the token on your server.

First step: Include simplify.js in your page

First, include simplify.js and its required dependency, jQuery, in the page:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.simplify.com/commerce/v1/simplify.js"></script>

Second Step: Create a single-use token

Now, from the card information that has been entered, you will create a single-use token. You should never store or attempt to reuse single-use tokens to prevent possible security issues. Next you will want to add a handler to your form. This handler will capture the submit event, and then use the credit card information to create a single-use token:

$(document).ready(function() {
    $("#simplify-payment-form").on("submit", function() {
        // Disable the submit button
        $("#process-payment-btn").attr("disabled", "disabled");
        // Generate a card token & handle the response
        SimplifyCommerce.generateToken({
            key: "YOUR_PUBLIC_KEY",
            card: {
                number: $("#cc-number").val(),
                cvc: $("#cc-cvc").val(),
                expMonth: $("#cc-exp-month").val(),
                expYear: $("#cc-exp-year").val()
            }
        }, simplifyResponseHandler);

        // Prevent the form from submitting
        return false;
    });
});

Notice the call to SimplifyCommerce.generateToken. The first argument is a JavaScript Object holding credit card data that was entered and your publishable Key . Use the publishable key for the appropriate environment (sandbox or live). In this example, we're using jQuery's val() to retrieve values entered in the credit card form.

The card number and expiration info is the minimum that should be provided. The complete list of fields you can provide is available in the simplify.js documentation .

The second argument simplifyResponseHandler is a callback that handles the response from Simplify Commerce. generateToken is an asynchronous call. It returns immediately and invokes simplifyResponseHandler when it receives a response from Simplify Commerces servers. Whatever function you pass should take two arguments, data and status:

status is a string describing the status.

data is an Object with these properties:

{
  id : "4b0abb46-35d0-44d1-a6b3-5e7e26b35ef2", // String of token identifier,
  card : {...}, // Dictionary of the card used to create the token
  used : false, // Boolean of whether this token has been used,
}

Third Step: Sending the form and data to your server

In the example, this is done in simplifyResponseHandler:

  • If the information returns an error, the error gets displayed on the page.
  • If the token was created successfully, you would then add the returned token to the form in the simplifyToken field and submit the form to the server.
function simplifyResponseHandler(data) {
    var $paymentForm = $("#simplify-payment-form");
    // Remove all previous errors
    $(".error").remove();
    // Check for errors
    if (data.error) {
        // Show any validation errors
        if (data.error.code == "validation") {
            var fieldErrors = data.error.fieldErrors,
                fieldErrorsLength = fieldErrors.length,
                errorList = "";
            for (var i = 0; i < fieldErrorsLength; i++) {
                errorList += "<div class='error'>Field: '" + fieldErrors[i].field +
                             "' is invalid - " + fieldErrors[i].message + "</div>";
            }
            // Display the errors
            $paymentForm.after(errorList);
        }
        // Re-enable the submit button
        $("#process-payment-btn").removeAttr("disabled");
    } else {
        // The token contains id, last4, and card type
        var token = data["id"];
        // Insert the token into the form so it gets submitted to the server
        $paymentForm.append("<input type='hidden' name='simplifyToken' value='" + token + "' />");
        // Submit the form to the server
        $paymentForm.get(0).submit();
    }
}

So we can add the token to the form, we're adding a new input tag into the form, and setting its value to the token. This allows you to send the token id to the server.

After we’ve added the info to the form, we re-submit the form (we waited for Simplify Commerce to tokenize the credit card details). We call submit() on the form directly to prevent an infinite loop. The data will be sent as an HTTP POST to the URL in the forms action.

Now, we put it all together into one page.

<h1>Charge $10 with Simplify Commerce</h1>
<form id="simplify-payment-form" action="" method="POST">
    <!-- The $10 amount is set on the server side -->
    <div>
        <label>Credit Card Number: </label>
        <input id="cc-number" type="text" maxlength="20" autocomplete="off" value="" autofocus />
    </div>
    <div>
        <label>CVC: </label>
        <input id="cc-cvc" type="text" maxlength="4" autocomplete="off" value=""/>
    </div>
    <div>
        <label>Expiry Date: </label>
        <select id="cc-exp-month">
            <option value="01">Jan</option>
            <option value="02">Feb</option>
            <option value="03">Mar</option>
            <option value="04">Apr</option>
            <option value="05">May</option>
            <option value="06">Jun</option>
            <option value="07">Jul</option>
            <option value="08">Aug</option>
            <option value="09">Sep</option>
            <option value="10">Oct</option>
            <option value="11">Nov</option>
            <option value="12">Dec</option>
        </select>
        <select id="cc-exp-year">
            <option value="15">2015</option>
            <option value="16">2016</option>
            <option value="17">2017</option>
            <option value="18">2018</option>
            <option value="19">2019</option>
            <option value="20">2020</option>
            <option value="21">2021</option>
            <option value="22">2022</option>
            <option value="23">2023</option>
            <option value="24">2024</option>
        </select>
    </div>
    <button id="process-payment-btn" type="submit">Process Payment</button>
</form>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.simplify.com/commerce/v1/simplify.js"></script>
<script type="text/javascript">
    function simplifyResponseHandler(data) {
        var $paymentForm = $("#simplify-payment-form");
        // Remove all previous errors
        $(".error").remove();
        // Check for errors
        if (data.error) {
            // Show any validation errors
            if (data.error.code == "validation") {
                var fieldErrors = data.error.fieldErrors,
                        fieldErrorsLength = fieldErrors.length,
                        errorList = "";

                for (var i = 0; i < fieldErrorsLength; i++) {
                    errorList += "<div class='error'>Field: '" + fieldErrors[i].field +
                            "' is invalid - " + fieldErrors[i].message + "</div>";
                }
                // Display the errors
                $paymentForm.after(errorList);
            }
            // Re-enable the submit button
            $("#process-payment-btn").removeAttr("disabled");
        } else {
            // The token contains id, last4, and card type
            var token = data["id"];
            // Insert the token into the form so it gets submitted to the server
            $paymentForm.append("<input type='hidden' name='simplifyToken' value='" + token + "' />");
            // Submit the form to the server
            $paymentForm.get(0).submit();
        }
    }

    $(document).ready(function() {
        $("#simplify-payment-form").on("submit", function() {
            // Disable the submit button
            $("#process-payment-btn").attr("disabled", "disabled");
            // Generate a card token & handle the response
            SimplifyCommerce.generateToken({
                key: "YOUR_PUBLIC_KEY",
                card: {
                    number: $("#cc-number").val(),
                    cvc: $("#cc-cvc").val(),
                    expMonth: $("#cc-exp-month").val(),
                    expYear: $("#cc-exp-year").val()
                }
            }, simplifyResponseHandler);

            // Prevent the form from submitting
            return false;
        });
    });
</script>

Adding MasterPass™ acceptance

You can also easily add MasterPass™ acceptance to your payment form through our MasterPass tutorial.

Charging a Card

Here we will show how to charge a card using the card token that was generated.

In the previous step, you created an HTML form that used simplify.js to generate a one-time use card token, and submitted that token to your server. To complete a payment, you need to use that token with one of the Simplify Commerce SDKs to create a Charge.

PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

Payment payment = Payment.create(new PaymentsMap()
        .set("amount", 1000)
        .set("currency", "USD")
        .set("description", "payment description")
        .set("reference", "7a6ef6be31")
        .set("token", "[TOKEN ID]")
);

if ("APPROVED".equals(payment.get("paymentStatus"))) {
    System.out.println("Payment approved");
}
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

payment = Simplify::Payment.create({
        "amount" => "1000",
        "token" => "[TOKEN ID]",
        "description" => "payment description",
        "reference" => "7a6ef6be31",
        "currency" => "USD"
})

if payment['paymentStatus'] == 'APPROVED'
    puts "Payment approved"
end
import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

payment = simplify.Payment.create({
        "amount" : "1000",
        "token" : "[TOKEN ID]",
        "description" : "payment description",
        "reference" : "7a6ef6be31",
        "currency" : "USD"

})

if payment.paymentStatus == 'APPROVED':
    print "Payment approved"
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$payment = Simplify_Payment::createPayment(array(
        'amount' => '1000',
        'token' => '[TOKEN ID]',
        'description' => 'payment description',
        'reference' => '7a6ef6be31',
        'currency' => 'USD'
));

if ($payment->paymentStatus == 'APPROVED') {
    echo "Payment approved\n";
}

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

my $payment = Net::Simplify::Payment->create({
    amount => "1000",
    token => "[TOKEN ID]",
    description => "payment description",
    reference => "7a6ef6be31",
    currency => "USD"
});

print "Payment status ", $payment->{paymentStatus}, "\n";
using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();

Payment payment = new Payment();
payment.Amount = 1000;
payment.Currency = "USD";
payment.Description = "payment description";
payment.Reference = "7a6ef6be31";
payment.Token = "[TOKEN ID]";

try
{
    payment = (Payment)api.Create(payment);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.payment.create({
    amount : "1000",
    token : "[TOKEN ID]",
    description : "payment description",
    reference : "7a6ef6be31",
    currency : "USD"
}, function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Payment Status: " + data.paymentStatus);
});

The example above charges $10 USD using the card associated with the card token you created in the payments form. You must supply your API Keys (for either Sandbox or Live mode).

Recurring Payments

Simplify Commerce supports setting up recurring payments for your customers. You will set up a payment plan and assign subscriptions to that plan to your customers. Simplify Commerce will then automatically invoice your customers each period with no additional effort required.

Create a Plan

The first step is to create a payment plan.

PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

Plan plan = Plan.create(new PaymentsMap()
        .set("amount", 1000L)
        .set("billingCycle", "FIXED")
        .set("billingCycleLimit", 4L)
        .set("frequency", "WEEKLY")
        .set("frequencyPeriod", 2L)
        .set("name", "plan2")
        .set("renewalReminderLeadDays", 7L)
);

System.out.println(plan);
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

plan = Simplify::Plan.create({
        "amount" => "1000",
        "renewalReminderLeadDays" => "7",
        "name" => "plan2",
        "billingCycle" => "FIXED",
        "frequency" => "WEEKLY",
        "billingCycleLimit" => "4",
        "frequencyPeriod" => "2"
})

puts plan.inspect
import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

plan = simplify.Plan.create({
        "amount" : "1000",
        "renewalReminderLeadDays" : "7",
        "name" : "plan2",
        "billingCycle" : "FIXED",
        "frequency" : "WEEKLY",
        "billingCycleLimit" : "4",
        "frequencyPeriod" : "2"

})

print plan
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$plan = Simplify_Plan::createPlan(array(
        'amount' => '1000',
        'renewalReminderLeadDays' => '7',
        'name' => 'plan2',
        'billingCycle' => 'FIXED',
        'frequency' => 'WEEKLY',
        'billingCycleLimit' => '4',
        'frequencyPeriod' => '2'
));

print_r($plan);

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

my $plan = Net::Simplify::Plan->create({
    amount => "1000",
    renewalReminderLeadDays => "7",
    name => "plan2",
    billingCycle => "FIXED",
    frequency => "WEEKLY",
    billingCycleLimit => "4",
    frequencyPeriod => "2"
});

print "Plan ID ", $plan->{id}, "\n";
using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();

Plan plan = new Plan();
plan.Amount = 1000;
plan.BillingCycle = "FIXED";
plan.BillingCycleLimit = 4;
plan.Frequency = "WEEKLY";
plan.FrequencyPeriod = 2;
plan.Name = "plan2";
plan.RenewalReminderLeadDays = 7;

try
{
    plan = (Plan)api.Create(plan);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.plan.create({
    amount : "1000",
    renewalReminderLeadDays : "7",
    name : "plan2",
    billingCycle : "FIXED",
    frequency : "WEEKLY",
    billingCycleLimit : "4",
    frequencyPeriod : "2"
}, function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Success Response: " + JSON.stringify(data));
});

The example above creates a monthly $10 payment plan.

Create a customer and subscribe to a plan

PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

Customer customer = Customer.create(new PaymentsMap()
        .set("card.cvc", "123")
        .set("card.expMonth", 11)
        .set("card.expYear", 19)
        .set("card.number", "5555555555554444")
        .set("email", "customer@mastercard.com")
        .set("name", "Customer Customer")
        .set("reference", "Ref1")
        .set("subscriptions[0].plan", "[PLAN ID]")
);

System.out.println(customer);
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

customer = Simplify::Customer.create({
        "subscriptions" => [
           {
              "plan" => "[PLAN ID]"
           }
        ],
        "email" => "customer@mastercard.com",
        "name" => "Customer Customer",
        "card" => {
           "expMonth" => "11",
           "expYear" => "19",
           "cvc" => "123",
           "number" => "5555555555554444"
        },
        "reference" => "Ref1"
})

puts customer.inspect
import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

customer = simplify.Customer.create({
        "subscriptions" : [
           {
              "plan" : "[PLAN ID]"
           }
        ],
        "email" : "customer@mastercard.com",
        "name" : "Customer Customer",
        "card" : {
           "expMonth" : "11",
           "expYear" : "19",
           "cvc" : "123",
           "number" : "5555555555554444"
        },
        "reference" : "Ref1"

})

print customer
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$customer = Simplify_Customer::createCustomer(array(
        'subscriptions' => array(
           array(
              'plan' => '[PLAN ID]'
           )
        ),
        'email' => 'customer@mastercard.com',
        'name' => 'Customer Customer',
        'card' => array(
           'expMonth' => '11',
           'expYear' => '19',
           'cvc' => '123',
           'number' => '5555555555554444'
        ),
        'reference' => 'Ref1'
));

print_r($customer);

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

my $customer = Net::Simplify::Customer->create({
    subscriptions => [
       {
          plan => "[PLAN ID]"
       }
    ],
    email => "customer\@mastercard.com",
    name => "Customer Customer",
    card => {
       expMonth => "11",
       expYear => "19",
       cvc => "123",
       number => "5555555555554444"
    },
    reference => "Ref1"
});

print "Customer ID ", $customer->{id}, "\n";
using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();

Customer customer = new Customer();
Card card = new Card();
card.Cvc = "123";
card.ExpMonth = 11;
card.ExpYear = 19;
card.Number = "5555555555554444";
customer.Card = card;
customer.Email = "customer@mastercard.com";
customer.Name = "Customer Customer";
customer.Reference = "Ref1";
List<Subscription> subscriptions = new List<Subscription>();
Subscription subscriptions1 = new Subscription();
subscriptions1.Plan = new Plan("[PLAN ID]");
subscriptions.Add(subscriptions1);
customer.Subscriptions = subscriptions;

try
{
    customer = (Customer)api.Create(customer);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.customer.create({
    subscriptions : [
       {
          plan : "[PLAN ID]"
       }
    ],
    email : "customer@mastercard.com",
    name : "Customer Customer",
    card : {
       expMonth : "11",
       expYear : "19",
       cvc : "123",
       number : "5555555555554444"
    },
    reference : "Ref1"
}, function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Success Response: " + JSON.stringify(data));
});

This creates a new customer and a subscription to the plan. You must assign a card when creating a customer. Now that the customer is assigned to the plan, an invoice will be generated by Simplify Commerce each period, and the customer’s card will be charged.

Adding one-time payments to an invoice

You can add additional one-time payments to a customer's next invoice

PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

InvoiceItem invoiceItem = InvoiceItem.create(new PaymentsMap()
        .set("amount", 1000L)
        .set("description", "Invoice Item1")
        .set("invoice", "[INVOICE ID]")
        .set("reference", "ref111")
);

System.out.println(invoiceItem);
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

invoiceItem = Simplify::InvoiceItem.create({
        "amount" => "1000",
        "description" => "Invoice Item1",
        "invoice" => "[INVOICE ID]",
        "reference" => "ref111"
})

puts invoiceItem.inspect
import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

invoiceItem = simplify.InvoiceItem.create({
        "amount" : "1000",
        "description" : "Invoice Item1",
        "invoice" : "[INVOICE ID]",
        "reference" : "ref111"

})

print invoiceItem
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$invoiceItem = Simplify_InvoiceItem::createInvoiceItem(array(
        'amount' => '1000',
        'description' => 'Invoice Item1',
        'invoice' => '[INVOICE ID]',
        'reference' => 'ref111'
));

print_r($invoiceItem);

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

my $invoiceItem = Net::Simplify::InvoiceItem->create({
    amount => "1000",
    description => "Invoice Item1",
    invoice => "[INVOICE ID]",
    reference => "ref111"
});

print "InvoiceItem ID ", $invoiceItem->{id}, "\n";
using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();

InvoiceItem invoiceItem = new InvoiceItem();
invoiceItem.Amount = 1000;
invoiceItem.Description = "Invoice Item1";
invoiceItem.Invoice = "[INVOICE ID]";
invoiceItem.Reference = "ref111";

try
{
    invoiceItem = (InvoiceItem)api.Create(invoiceItem);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.invoiceitem.create({
    amount : "1000",
    description : "Invoice Item1",
    invoice : "[INVOICE ID]",
    reference : "ref111"
}, function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Success Response: " + JSON.stringify(data));
});

This adds a one time payment of $10 USD to the customer's next invoice.

Applying Coupons

You can also create and apply coupons to subscriptions

Create a coupon

PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

Coupon coupon = Coupon.create(new PaymentsMap()
        .set("couponCode", "20off")
        .set("description", "20% off!")
        .set("endDate", 64063288800000L)
        .set("maxRedemptions", 100)
        .set("percentOff", 20L)
        .set("startDate", 2394829384000L)
);

System.out.println(coupon);
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

coupon = Simplify::Coupon.create({
        "startDate" => "2394829384000",
        "description" => "20% off!",
        "maxRedemptions" => "100",
        "couponCode" => "20off",
        "endDate" => "64063288800000",
        "percentOff" => "20"
})

puts coupon.inspect
import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

coupon = simplify.Coupon.create({
        "startDate" : "2394829384000",
        "description" : "20% off!",
        "maxRedemptions" : "100",
        "couponCode" : "20off",
        "endDate" : "64063288800000",
        "percentOff" : "20"

})

print coupon
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$coupon = Simplify_Coupon::createCoupon(array(
        'startDate' => '2394829384000',
        'description' => '20% off!',
        'maxRedemptions' => '100',
        'couponCode' => '20off',
        'endDate' => '64063288800000',
        'percentOff' => '20'
));

print_r($coupon);

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

my $coupon = Net::Simplify::Coupon->create({
    startDate => "2394829384000",
    description => "20% off!",
    maxRedemptions => "100",
    couponCode => "20off",
    endDate => "64063288800000",
    percentOff => "20"
});

print "Coupon ID ", $coupon->{id}, "\n";
using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();

Coupon coupon = new Coupon();
coupon.CouponCode = "20off";
coupon.Description = "20% off!";
coupon.EndDate = 64063288800000;
coupon.MaxRedemptions = 100;
coupon.PercentOff = 20;
coupon.StartDate = 2394829384000;

try
{
    coupon = (Coupon)api.Create(coupon);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.coupon.create({
    startDate : "2394829384000",
    description : "20% off!",
    maxRedemptions : "100",
    couponCode : "20off",
    endDate : "64063288800000",
    percentOff : "20"
}, function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Success Response: " + JSON.stringify(data));
});

The example above creates a new coupon. You will use the ID of the newly created coupon to create or modify a subscription. You must supply your API Keys (for either Sandbox or Live mode).

Applying coupon to a subscription

PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

Subscription subscription = Subscription.create(new PaymentsMap()
        .set("coupon", "[COUPON ID]")
        .set("customer", "[CUSTOMER ID]")
        .set("plan", "[PLAN ID]")
);

System.out.println(subscription);
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

subscription = Simplify::Subscription.create({
        "plan" => "[PLAN ID]",
        "customer" => "[CUSTOMER ID]",
        "coupon" => "[COUPON ID]"
})

puts subscription.inspect
import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

subscription = simplify.Subscription.create({
        "plan" : "[PLAN ID]",
        "customer" : "[CUSTOMER ID]",
        "coupon" : "[COUPON ID]"

})

print subscription
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$subscription = Simplify_Subscription::createSubscription(array(
        'plan' => '[PLAN ID]',
        'customer' => '[CUSTOMER ID]',
        'coupon' => '[COUPON ID]'
));

print_r($subscription);

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

my $subscription = Net::Simplify::Subscription->create({
    plan => "[PLAN ID]",
    customer => "[CUSTOMER ID]",
    coupon => "[COUPON ID]"
});

print "Subscription ID ", $subscription->{id}, "\n";
using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();

Subscription subscription = new Subscription();
subscription.Coupon = new Coupon("[COUPON ID]");
subscription.Customer = new Customer("[CUSTOMER ID]");
subscription.Plan = new Plan("[PLAN ID]");

try
{
    subscription = (Subscription)api.Create(subscription);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.subscription.create({
    plan : "[PLAN ID]",
    customer : "[CUSTOMER ID]",
    coupon : "[COUPON ID]"
}, function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Success Response: " + JSON.stringify(data));
});

This example creates a subscription using a coupon. Note that if the coupon you are applying has expired, the subscription request will not be processed.

Refunding a Payment

You may also need to refund part or all of a charge

PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

Refund refund = Refund.create(new PaymentsMap()
        .set("amount", 100L)
        .set("payment", "[PAYMENT ID]")
        .set("reason", "Refund Description")
        .set("reference", "76398734634")
);

System.out.println(refund);
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

refund = Simplify::Refund.create({
        "amount" => "100",
        "payment" => "[PAYMENT ID]",
        "reason" => "Refund Description",
        "reference" => "76398734634"
})

puts refund.inspect
import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

refund = simplify.Refund.create({
        "amount" : "100",
        "payment" : "[PAYMENT ID]",
        "reason" : "Refund Description",
        "reference" : "76398734634"

})

print refund
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$refund = Simplify_Refund::createRefund(array(
        'amount' => '100',
        'payment' => '[PAYMENT ID]',
        'reason' => 'Refund Description',
        'reference' => '76398734634'
));

print_r($refund);

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

my $refund = Net::Simplify::Refund->create({
    amount => "100",
    payment => "[PAYMENT ID]",
    reason => "Refund Description",
    reference => "76398734634"
});

print "Refund ID ", $refund->{id}, "\n";
using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();

Refund refund = new Refund();
refund.Amount = 100;
refund.Payment = new Payment("[PAYMENT ID]");
refund.Reason = "Refund Description";
refund.Reference = "76398734634";

try
{
    refund = (Refund)api.Create(refund);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.refund.create({
    amount : "100",
    payment : "[PAYMENT ID]",
    reason : "Refund Description",
    reference : "76398734634"
}, function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Success Response: " + JSON.stringify(data));
});

This example assumes you have previously created a charge, and uses that ID. $1.00 is refunded to the card associated with the original charge.

Payment Auth/Capture

An authorization is very similar to a payment, except that instead of immediately exchanging money between you and your customer, you place a temporary hold on the customer's account and can then later capture an amount of less than or equal to the amount authorized, releasing the difference back to the customer. It may be important to create an authorization if a customer makes a purchase but there is a delay between acceptance of the customer's payment information and shipping of the item(s) purchased.

Authorizing a Payment

Here we will show how to authorize a card payment using a card token similar to the one you generated if you have been following the tutorial so far. Otherwise, click here to learn about generating card tokens. To authorize a payment, you need to use a card token with the Simplify Commerce Authorization SDK to create the authorization.

PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

Authorization authorization = Authorization.create(new PaymentsMap()
        .set("amount", 1000)
        .set("currency", "USD")
        .set("description", "payment description")
        .set("reference", "7a6ef6be31")
        .set("token", "[TOKEN ID]")
);

System.out.println(authorization);
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

authorization = Simplify::Authorization.create({
        "amount" => "1000",
        "token" => "[TOKEN ID]",
        "description" => "payment description",
        "reference" => "7a6ef6be31",
        "currency" => "USD"
})

puts authorization.inspect
import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

authorization = simplify.Authorization.create({
        "amount" : "1000",
        "token" : "[TOKEN ID]",
        "description" : "payment description",
        "reference" : "7a6ef6be31",
        "currency" : "USD"

})

print authorization
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$authorization = Simplify_Authorization::createAuthorization(array(
        'amount' => '1000',
        'token' => '[TOKEN ID]',
        'description' => 'payment description',
        'reference' => '7a6ef6be31',
        'currency' => 'USD'
));

print_r($authorization);

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

my $authorization = Net::Simplify::Authorization->create({
    amount => "1000",
    token => "[TOKEN ID]",
    description => "payment description",
    reference => "7a6ef6be31",
    currency => "USD"
});

print "Authorization ID ", $authorization->{id}, "\n";
using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();

Authorization authorization = new Authorization();
authorization.Amount = 1000;
authorization.Currency = "USD";
authorization.Description = "payment description";
authorization.Reference = "7a6ef6be31";
authorization.Token = "[TOKEN ID]";

try
{
    authorization = (Authorization)api.Create(authorization);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.authorization.create({
    amount : "1000",
    token : "[TOKEN ID]",
    description : "payment description",
    reference : "7a6ef6be31",
    currency : "USD"
}, function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Success Response: " + JSON.stringify(data));
});

Capturing an Authorization

Most of the time, creating an authorization will eventually be followed by capturing a payment. To capture a payment, use the same command as you normally would to create a payment, but instead of specifying a card token or card information, you will reference an authorization ID. Make sure that the capture currency is the same as the authorization currency and that the amount captured is equal to or less than the authorization amount.

PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

Payment payment = Payment.create(new PaymentsMap()
        .set("amount", 2500)
        .set("authorization", "[AUTHORIZATION ID]")
        .set("currency", "USD")
        .set("description", "shipment of two eggs in a glass bottle")
        .set("reference", "BCK2THEST")
        .set("replayId", "A-77633219")
);

if ("APPROVED".equals(payment.get("paymentStatus"))) {
    System.out.println("Payment approved");
}
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

payment = Simplify::Payment.create({
        "replayId" => "A-77633219",
        "amount" => "2500",
        "description" => "shipment of two eggs in a glass bottle",
        "authorization" => "[AUTHORIZATION ID]",
        "reference" => "BCK2THEST",
        "currency" => "USD"
})

if payment['paymentStatus'] == 'APPROVED'
    puts "Payment approved"
end
import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

payment = simplify.Payment.create({
        "replayId" : "A-77633219",
        "amount" : "2500",
        "description" : "shipment of two eggs in a glass bottle",
        "authorization" : "[AUTHORIZATION ID]",
        "reference" : "BCK2THEST",
        "currency" : "USD"

})

if payment.paymentStatus == 'APPROVED':
    print "Payment approved"
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$payment = Simplify_Payment::createPayment(array(
        'replayId' => 'A-77633219',
        'amount' => '2500',
        'description' => 'shipment of two eggs in a glass bottle',
        'authorization' => '[AUTHORIZATION ID]',
        'reference' => 'BCK2THEST',
        'currency' => 'USD'
));

if ($payment->paymentStatus == 'APPROVED') {
    echo "Payment approved\n";
}

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

my $payment = Net::Simplify::Payment->create({
    replayId => "A-77633219",
    amount => "2500",
    description => "shipment of two eggs in a glass bottle",
    authorization => "[AUTHORIZATION ID]",
    reference => "BCK2THEST",
    currency => "USD"
});

print "Payment status ", $payment->{paymentStatus}, "\n";
using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();

Payment payment = new Payment();
payment.Amount = 2500;
payment.Authorization = new Authorization("[AUTHORIZATION ID]");
payment.Currency = "USD";
payment.Description = "shipment of two eggs in a glass bottle";
payment.Reference = "BCK2THEST";
payment.ReplayId = "A-77633219";

try
{
    payment = (Payment)api.Create(payment);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}
var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.payment.create({
    replayId : "A-77633219",
    amount : "2500",
    description : "shipment of two eggs in a glass bottle",
    authorization : "[AUTHORIZATION ID]",
    reference : "BCK2THEST",
    currency : "USD"
}, function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Payment Status: " + data.paymentStatus);
});

Reversing an Authorization

Sometimes, you might wish to cancel an authorization as you would void a payment. Reversing an authorization is easy using the Simplify Commerce SDK. Keep in mind that you cannot reverse an authorization that has already been captured and that you cannot re-authorize a reversed authorization.

PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

Authorization authorization = Authorization.find("4TR6Bc");

authorization = authorization.delete();

System.out.println(authorization);
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

authorization = Simplify::Authorization.find('4TR6Bc')

authorization = authorization.delete()

puts authorization.inspect
import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

authorization = simplify.Authorization.find('4TR6Bc')
authorization.delete()
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$obj  = Simplify_Authorization::findAuthorization('4TR6Bc');

$obj = $obj->deleteAuthorization();

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

$authorization = Net::Simplify::Authorization->find('4TR6Bc');

$authorization->delete();

using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();


try
{
    String id = "1234";

    Authorization authorization = (Authorization)api.Find(typeof(Authorization), id);

    authorization = (Authorization)api.Delete(typeof(Authorization), authorization.Id);

    Console.WriteLine (authorization.Id);
}
catch (Exception e)
{
    Console.WriteLine(e.ToString());
}

var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.authorization.delete("4TR6Bc", function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Success Response: " + JSON.stringify(data));
});

Using Webhooks

Webhooks, which are URLs that will receive events as they happen on your account. For instance, whenever a new charge is created, Simplify Commerce will send an HTTP POST with a new charge to any of your Webhooks.

Each event is POSTed as JSON in the following format:

{
    event: {
        name: "[event name]"
        data: {
            [event data]
        }
    }
}

Event data is the JSON representation of the associated object, such as a charge

Example:

{
  "event": {
    "name": "payment.create",
    "data": {
      "card": {
        "id": "8i5RMT",
        "type": "MASTERCARD",
        "last4": "4444",
        "expMonth": 12,
        "expYear": 14,
        "dateCreated": 1380548895740
      },
      "disputed": false,
      "amount": 1100,
      "amountRemaining": 1100,
      "currency": "USD",
      "refunded": false,
      "authCode": "1380548896616",
      "paymentStatus": "APPROVED",
      "dateCreated": 1380548896633,
      "paymentDate": 1380548896617,
      "id": "5c8jzi",
      "fee": 61
    }
  }
}

The JSON data posted to the webhook is formatted as a JSON Web Signatures (JWS) message and must be decoded by creating an Event object which also verifies the integrity of the message. The following code sample shows how to create an Event object by passing in the posted data:


PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

String requestData = ....

Event event = Event.create(new PaymentsMap().set("payload", requestData));

String name = event.get("name").toString();
System.out.println("Event '" + name + "'");

Map data = (Map) event.get("data");
System.out.println("Event '" + name + "'");

require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

requestData = ...

event = Simplify::Event.create({'payload' => requestData})

puts "Event name #{event['name']}"

data = event['data']

import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

requestData = ...

event = simplify.Event.create({'payload' => requestData})

print "event name is ", event.name
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

$event = Simplify_Event::createEvent(array(
    'payload' => $HTTP_RAW_POST_DATA
));

$name = $event->name;
$data = $event->data;

echo "Event is " . $name . "\n";

?>

use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

$requestData = ...

$event = Net::Simplify::Event->create({payload => requestData})

print "Event name ", $event->{name}, "\n";

$data = $event->{data};

using SimplifyCommerce.Payments;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

string data = "RAW POST DATA FROM WEBHOOK";

PaymentsApi api = new PaymentsApi();

JObject obj = api.JwsDecode(data); // Raw Json

Payment p = (Payment)api.extractObjectFromEvent(obj); // Get object

var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

var requestData = {};

client.event.create({
    payload : requestData,
    url: 'WEBHOOK_URL'
}, function(errData, data){

    if(errData){
        console.error("Error Message: " + errData.data.error.message);
        // handle the error
        return;
    }

    console.log("Event Name: " + data.name);
});

Have a look at the webhook reference for a list of the different types of events that are emitted.

Handling Errors

Any errors processing a request by the API are handled with exceptions that provide detailed information on the cause of the error.


PaymentsApi.PUBLIC_KEY = "YOUR_PUBLIC_API_KEY";
PaymentsApi.PRIVATE_KEY = "YOUR_PRIVATE_API_KEY";

try {
    Payment payment = Payment.create(new PaymentsMap()
            .set("card.number", "5555555555554445")
            .set("card.cvc", "123")
            .set("card.expMonth", "12")
            .set("card.expYear", "11")
            .set("currency", "USD")
            .set("amount", 1234L)
            .set("description", "Invalid payment"));

} catch (ApiException e) {
    System.out.println("Message:    " + e.getMessage());
    System.out.println("Reference:  " + e.getReference());
    System.out.println("Error code: " + e.getErrorCode());
    if (e instanceof InvalidRequestException) {
        InvalidRequestException e2 = (InvalidRequestException) e;
        if (e2.hasFieldErrors()) {
            for (InvalidRequestException.FieldError fe : e2.getFieldErrors()) {
                System.out.println(fe.getFieldName()
                       + ": '" + fe.getMessage()
                       + "' (" + fe.getErrorCode() + ")");
            }
        }
    }
}
require 'simplify'

Simplify::public_key = "YOUR_PUBLIC_API_KEY"
Simplify::private_key = "YOUR_PRIVATE_API_KEY"

begin

  payment = Simplify::Payment.create({
        "card" => {
            "number" => "5555555555554445",
            "cvc" => "123",
            "expMonth" => 12,
            "expYear" => 10
        },
        "currency" => "USD",
        "amount" => 1234,
        "description" => "Invalid payment"
  })

rescue Simplify::ApiException => e
  puts "Message:      #{e.message}"
  puts "Reference:    #{e.reference}"
  puts "Error code:   #{e.errorCode}"
  if e.is_a?(Simplify::BadRequestException) and
      e.fieldErrors.each do |fieldError|
        puts "#{fieldError.fieldName} '#{fieldError.message}' (#{fieldError.errorCode})"
      end
    end
  end
end

import simplify

simplify.public_key = "YOUR_PUBLIC_API_KEY"
simplify.private_key = "YOUR_PRIVATE_API_KEY"

try:
    payment = simplify.Payment.create({
               "card" : {
                   "number": '5555555555554445',
                   "cvc": '123',
                   "expMonth": '12',
                   "expYear": '11'
               },
               "currency" : "USD",
               "amount": 1234,
               "description": "Invalid payment"
    })

except simplify.ApiError as e:
    print "Message      " + str(e.message)
    print "Reference    " + str(e.reference)
    print "ErrorCode    " + str(e.error_code)
    if isinstance(e, simplify.BadRequestError) and e.has_field_errors:
        for field_error in e.field_errors:
            print field_error.field_name + ": '" + field_error.message \
                + "' (" + field_error.error_code + ")"
<?php

require_once("./lib/Simplify.php");

Simplify::$publicKey = 'YOUR_PUBLIC_API_KEY';
Simplify::$privateKey = 'YOUR_PRIVATE_API_KEY';

try {

    $payment = Simplify_Payment::createPayment(array(
        "card" => array(
            "number" => "5555555555554445",
            "cvc" => "123",
            "expMonth" => 12,
            "expYear" => 12
        ),
        "currency" => "USD",
        "amount" => 1234,
        "description" => "Invalid payment"
    ));

} catch (Simplify_ApiException $e) {
    print "Reference:   " . $e->getReference() . "\n";
    print "Message:     " . $e->getMessage() . "\n";
    print "Error code:  " . $e->getErrorCode() . "\n";
    if ($e instanceof Simplify_BadRequestException && $e->hasFieldErrors()) {
        foreach ($e->getFieldErrors() as $fieldError) {
            print $fieldError->getFieldName()
                . ": '" . $fieldError->getMessage()
                . "' (" . $fieldError->getErrorCode()
                . ")\n";
        }
    }
}

?>
use Net::Simplify;

$Net::Simplify::public_key = "YOUR_PUBLIC_API_KEY";
$Net::Simplify::private_key = "YOUR_PRIVATE_API_KEY";

eval {
  my $payment = Net::Simplify::Payment->create({
        card => {
            number => "5555555555554445",
            cvc => "123",
            expMonth => 12,
            expYear => 10
        },
        currency => "USD",
        amount => 1234,
        description => "Invalid payment"
  });
};
if ($@) {
    if ($@->isa('Net::Simplify::ApiException')) {
        print "Message:    ", $@->message, "\n";
        print "Reference:  ", $@->reference, "\n";
        print "Error Code: ", $@->code, "\n";

        if ($@->isa('Net::Simplify::BadRequestException')) {
            foreach my $field_error ($@->field_errors) {
                my $code = $field_error->code;
                my $field =
                my $msg = $field_error->message;
                print $field_error->field, " '", $field_error->message, "' (",
                        $field_error->code, ")\n";
            }
        }
    }
}

using SimplifyCommerce.Payments;

PaymentsApi.PublicApiKey = "YOUR_PUBLIC_KEY";
PaymentsApi.PrivateApiKey = "YOUR_PRIVATE_KEY";

PaymentsApi api = new PaymentsApi();

Payment payment = new Payment();
payment.Amount = 1000;
payment.Currency = "USD";
payment.Description = "payment description";
payment.Token = "[TOKEN ID]";

try
{
    payment = (Payment)api.Create(payment);
}
catch (ApiException e)
{
    Console.WriteLine("Message: " + e.Message);
    Console.WriteLine("Error details: " + e.ErrorData);
}


var Simplify = require("simplify-commerce"),
    client = Simplify.getClient({
        publicKey: 'YOUR_PUBLIC_API_KEY',
        privateKey: 'YOUR_PRIVATE_API_KEY'
    });

client.payment.create({
    "card" : {
        "number": '5555555555554445', // Invalid card number
        "cvc": '123',
        "expMonth": '12',
        "expYear": '11'
    },
    "currency" : "USD",
    "amount": 1234,
    "description": "Invalid payment"
}, function(errData, data){

    if(errData){
        var error = errData.data.error;
        console.error("Error Message: " + error.message);
        console.error("Error Reference: " + error.reference);
        console.error("Error Code: " + error.error_code);
        // handle the error
        return;
    }

    console.log("Payment Status: " + data.paymentStatus);
});