Enterprise Java

J2Pay – Complete Example

Introduction

In this section we will be looking in great detail of how to use a gateway and invoke all four methods successfully i.e. purchase, refund, void and rebill.

For this example we will be using Authorize gateway. Let’s begin.

First of all we will get the Authorize gateway object.

Gateway gateway = GatewayFactory.getGateway(AvailableGateways.AUTHORIZE);

But what if you would like to fetch the Authorize gateway dynamically for example you are getting its name from database.

Here is how you could do this.

Gateway gateway = GatewayFactory.getGateway(AvailableGateways.valueOf("AUTHORIZE"));

Know you can understand both two approaches of how to get your desired gateway object.

Since we are working in test environment second thing we will do is enable the test mode.

gateway.setTestMode(true);

Note: Test mode will only work if it is supported by gateway otherwise it will be ignored by library.

Next and most important thing is API parameters, these are the unique values provided my merchant service providers i.e. API user name and password which must be included in all requests and these are always different for all gateways.

Since we are using J2pay we do not need to read any documentation for authorize gateway variables.

This is where you will be using sample parameter methods (see Sample Parameters section)

Here is how you will do that.

JSONObject apiSampleParameters = gateway.getApiSampleParameters();

Now we will print it to see what the parameters are.

JSONObject apiSampleParameters = gateway.getApiSampleParameters();
    System.out.println(apiSampleParameters);
    
    //output
    { "name" : "also called api user name / api login id", "transactionKey" : "the transaction key" }

As you can see for Authorize API parameters are name and transactionKey. We will populate these values and pass to purchase method.

apiSampleParameters.put("name", "<your acount's user name here>");
apiSampleParameters.put("transactionKey", "<your account's transaction key here>");

Purchase

Purchase method requires five parameters.

  1. JSONObject apiParamters, that is the gateway specific paramters always unique for each gateway.
  2. Customer customer, this class represents customer personal information.
  3. CustomerCard customerCard, this class represents the Customer card details.
  4. Currency currency, that is enum contains the list of currency in which amount will be charged.
  5. float amount, the amout that will be charged.

We have already set the apiParameters above.

Now creating customer and customer card object.

Note: Customer and customercard classes support chaining setter methods and all field used below are required.

Customer customer = new Customer();
        
    customer
        .setFirstName("test first name")
        .setLastName("test last name")
        .setCountry(Country.US)
        .setState("TX")
        .setCity("test city")
        .setAddress("test address")
        .setZip("12345")
        .setPhoneNumber("1234567890")
        .setEmail("email@domain.com")
        .setIp("127.0.0.1");

    CustomerCard customerCard = new CustomerCard();

    customerCard
        .setName("test card name")
        .setNumber("5424000000000015")
        .setCvv(123)
        .setExpiryMonth("01")
        .setExpiryYear("2022");

Note: 4th and 5th parameters does not require any explanation.

Now all parameters are ready we can pass them to purchase methods

HTTPResponse response = gateway.purchase(apiSampleParameters, customer, customerCard, Currency.USD, 45);

You can check the status of purchase request by calling isSuccessful method and you can also get the JSON response by calling getJSONResponse method.

response.isSuccessful();
    response.getJSONResponse();

Let’s put all code together.

Gateway gateway = GatewayFactory.getGateway(AvailableGateways.AUTHORIZE);
    JSONObject apiSampleParameters = gateway.getApiSampleParameters();

    apiSampleParameters.put("name", "");
    apiSampleParameters.put("transactionKey", "");

    Customer customer = new Customer();

    customer
        .setFirstName("test first name")
        .setLastName("test last name")
        .setCountry(Country.US)
        .setState("TX")
        .setCity("test city")
        .setAddress("test address")
        .setZip("12345")
        .setPhoneNumber("1234567890");

    CustomerCard customerCard = new CustomerCard();
    
    customerCard
        .setName("test card name")
        .setNumber("5424000000000015")
        .setCvv(123)
        .setExpiryMonth("01")
        .setExpiryYear("2022");
        
    gateway.setTestMode(true);

    HTTPResponse response = gateway.purchase(apiSampleParameters, customer, customerCard, Currency.USD, 45);

    System.out.println (response.isSuccessful());
    System.out.println (response.getJSONResponse());

Let’s take a look at response we receive. Consider we are holding response in response variable.

JSONObject response = response.getJSONResponse();

After printing response here is what we got.

{
        "lr": {
            "amount": 2.5,
            "cardExpiryYear": "2017",
            "message": "This transaction has been approved.",
            "cardFirst6": "542400",
            "cardExpiryMonth": "12",
            "transactionId": "60036012175",
            "maskedCard": "542400******0015",
            "rebillParams": {
                "customerProfileId": "1813844918",
                "paymentProfileId": "1808509554"
            },
            "success": true,
            "voidParams": {
                "transactionId": "60036012175"
            },
            "currencyCode": "USD",
            "cardLast4": "0015",
            "refundParams": {
                "transactionId": "60036012175",
                "cardLast4": "0015"
            }
        },
        "gr": { //long gateway response }
    }

As you can see for further transaction like refund, void or rebill library itself created the required parameters

For rebill

"rebillParams": {
        "customerProfileId": "1813844918",
        "paymentProfileId": "1808509554"
    },

For void

"voidParams": {
        "transactionId": "60036012175"
    },

For refund

"refundParams": {
        "transactionId": "60036012175",
        "cardLast4": "0015"
    }

Note: You can save these parmeters in database and pass them to suitable methods.

Rebill

For rebill we will call the getRebillSampleParameters method.

JSONObject rebillSampleParameters = gateway.getRebillSampleParameters();

After printing it you will see.

{"customerProfileId":"the customer profile id","paymentProfileId":"the customer payment profile id"}

If you match that with above purchase response rebillParams key you will see actually there is no difference. Purchase response already contains these parameters with populated values.

So we are not creating them like getApiSampleParameters above but if you have not executed the purchase transaction from this library you have second option to create these parameters and pass them to rebill method. Below we have described both approaches so you could use whatever suits you better.

First Approach

This approach is fast forward. We will be using library generated parameters (rebillParams).

Since rebill method required three parameters

  1. JSON apiParameters
  2. JSON rebillParameters
  3. float amount

We have already discussed the apiParameters and just to remind you we saved gateway object in gateway variable and purchase response in response variable.

Here is how we could easily call the rebill method.

JSONObject rebillParams = response.getJSONObject("lr").getJSONObject("rebillParams")
    HTTPResponse rebillResponse = gateway.rebill(apiSampleParameters, rebillParams, 105);

Wasn’t that simple just two lines?

Second Approach

Second method is similar as we created apiParameters.

JSONObject rebillParams = gateway.getRebillSampleParameters();

After printing rebillParams we got.

System.out.println(rebillParams);
    
    //output
    {"customerProfileId":"the customer profile id","paymentProfileId":"the customer payment profile id"}

Now we will populate these values.

rebillParams.put("customerProfileId", "1813844918");
    rebillParams.put("paymentProfileId", "1808509554");

Now we can call rebill method.

HTTPResponse rebillResponse = gateway.rebill(apiSampleParameters, rebillParams, 105);

As you have seen above you can call the rebillResponse. getJSONResponse() method the get the response. And you could also check for whether the transaction was success or not by calling the rebillResponse.isSuccessful() method.

you can also notice both approaches are really simple and you are free to use whatever suits you better but it is recommended to use first approach as it is also very simple and excludes the chances of any bug.

Note: For rest of the example we will be using first approach.

Refund

Refund method required three parameters

  1. JSON apiParameters
  2. JSON refundParameters
  3. float amount

It is very similar to refund. That’s how we will call refund method.

JSONObject refundParams = response.getJSONObject("lr").getJSONObject("refundParams")
    HTTPResponse refundResponse = gateway.refund(apiSampleParameters, refundParams, 2.5);

Note: Rest of the work will remain same refundResponse contains the actual response.

Void

voidTransaction method requires two parameters.

  1. JSON apiParameters
  2. JSON voidParameters

Below is the sample code.

JSONObject voidParams= response.getJSONObject("lr").getJSONObject("voidParams")
    HTTPResponse voidResponse = gateway.voidTransaction (apiSampleParameters, voidParams);

Note: Rest of the work will remain same voidResponse contains the actual response.

Congratulations on completing example. You have fully understand the library.

Published on Java Code Geeks with permission by Muhhamad Ilyas, partner at our JCG program. See the original article here: Example

Opinions expressed by Java Code Geeks contributors are their own.

Muhammad Ilyas

Muhammad is a senior Software Engineer having expertise in famous programming languages like Java, php, c#, perl. He has also worked on mysql and mongodb. He is a co-founder of J2pay.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button