Integration Between GlobalPay and Salesforce

 

 

May 24, 2023

In this blog post, we talk about integration between GlobalPay and Salesforce using Rest API in Apex.

After completing this unit, you’ll be able to:

 

What is GlobalPay?

Global Payments provides payment services directly to merchants and indirectly through other financial organizations.

 

Create Access Token using API

Access token is required to execute all APIs without access token we can not make API calls.

Using your app credentials, send a request to create a bearer access token that can be used to execute subsequent API actions. The actions that the token can execute are determined by the permissions the app has.

Base url : https://apis.sandbox.globalpay.com

EndPoint : https://apis.sandbox.globalpay.com/ucp/accesstoken

Method : POST

Header Params:

content-type required string example: application/json
x-gp-version required string example: 2023-05-23

 

Request Body Params:

app_id required string example: U1lRHKomEn7DN907RCDPxVhyMfiMLcfy...
nonce required string example: random_string
secret required string example: e776ce1d9e94d5072ee132258e446cd92668d7c28..
grant_type required string example: client_credentials

 

You can find app_id and secret (App Key) from your GlobalPay Account like this:

 

Request Body Sample:

{

    "app_id": "i9R0byBBor6RqTQNj3g4MuVBwH5rd7yR",

    "nonce": "random_string",

    "secret": 668d7c28b2e475a345319b475ba601956c16e3983926ce279db6301d78b7f16",

    "grant_type": "client_credentials"

}

 

Now To get access token using Rest API write below apex code in your apex class.

public static Map<String, String> getToken()

    {

        String DATETIME_DATABASE_FORMAT = 'yyyy-MM-dd\'T\'HH:mm:ss\'Z\'';

        String nonce = Datetime.now().format(DATETIME_DATABASE_FORMAT); 

        

        Blob digest = Crypto.generateDigest('SHA-512', Blob.valueOf(nonce+''+appKey));

        String secretKey = EncodingUtil.convertToHex(digest);

        String endPoint = endPointURL + '/ucp/accesstoken';

        Map<String, String> mapBody = new Map<String, String>();

        mapBody.put('app_id', appId);

        mapBody.put('secret', secretKey);

        mapBody.put('grant_type','client_credentials');

        mapBody.put('nonce', nonce);

        String tokenBody = JSON.serialize(mapBody);

        

        HttpRequest req = new HttpRequest();

        req.setBody(tokenBody);

        req.setEndpoint(endPoint);

        req.setMethod('POST');

        req.setHeader('X-GP-Version', version);

        req.setHeader('Content-Type', 'application/json');

        req.setTimeout(60000);

        Http http = new Http();

        HTTPResponse res = http.send(req);

        Map<String, Object> deserializedBody =  (Map<String, Object>)JSON.deserializeUntyped(res.getBody());

        String token = (String)deserializedBody.get('token');

        String seconds_to_expire = String.ValueOf(deserializedBody.get('seconds_to_expire'));

        Map<String, String> tokenresult = new Map<String, String>();

        tokenresult.put('token', token);

        tokenresult.put('seconds_to_expire', seconds_to_expire);

        return tokenresult;

    }

 

 

After running above code the response will look like this:

Response:

 

 

Create Transaction using API

Base url : https://apis.sandbox.globalpay.com

EndPoint : https://apis.sandbox.globalpay.com/ucp/transactions 

Method : POST

 

Header Parameters

Authorization required string example: Bearer G3FA4TuYGCBiCWs4YpzrALGCYXZJ
x-gp-version required string

example: 2021-03-22

Content-type required string example: application/json

 

Request Body Sample

{

    "account_name": "Transaction_Processing",

    "type": "SALE",

    "channel": "CNP",

    "amount": "1999",

    "currency": "USD",

    "reference": "93459c78-f3f9-427c-84df-ca0584bb55bf",

    "country": "US",

    "payment_method": {

        "name": "James Mason",

        "entry_mode": "ECOM",

        "authentication": "id:'AUT_a234sdgsfg-H3u9-c66d-7a2q-sdgf9345mas24'",

        "card": {

            "number": "4263970000005262",

            "expiry_month": "05",

            "expiry_year": "25",

            "cvv": "852",

            "cvv_indicator": "PRESENT",

            "avs_address": "Flat 123",

            "avs_postal_code": "50001"

        }

    }

}

 

Write below apex code to create a transaction using Rest API.

 

@InvocableMethod(label='Make Payment' description='Provide the card information for payment' callout = 'true')

    public static List<String> cardPayment(List<Requests> requestList)

    {

        List<String> result = new List<String>();

        Boolean resetToken = false;

        GlobalPaymentsService gp = new GlobalPaymentsService();

        for(Requests reqrecord : requestList)

        {

            Integer amount = reqrecord.amount;

            String name = reqrecord.name;

            String card_number = reqrecord.card_number;

            String card_expiry_month =reqrecord.card_expiry_month;

            String card_expiry_year = reqrecord.card_expiry_year;

            String card_cvv = reqrecord.cvv;

            String card_avs_address = reqrecord.avs_address;

            String card_avs_postal_code = reqrecord.avs_postal_code;

            

            Map<String, String> tokenresult = new Map<String, String>();           

            if(tokenExpiredTime == null || tokenExpiredTime < Datetime.now())

            {

                tokenresult = getToken();

                token = tokenresult.get('token');            

                tokenExpiredTime = Datetime.now().addSeconds(Integer.valueOf(tokenresult.get('seconds_to_expire')));

                resetToken = true;          

            }

            String endPoint = endPointURL + '/ucp/transactions';

            Map<String, String> cardDetails = new Map<String, String>();

            cardDetails.put('number', card_number);

            cardDetails.put('expiry_month', card_expiry_month);

            cardDetails.put('expiry_year',card_expiry_year);

            cardDetails.put('cvv',card_cvv);

            cardDetails.put('cvv_indicator','PRESENT');

            cardDetails.put('avs_address',card_avs_address);

            cardDetails.put('avs_postal_code',card_avs_postal_code);

            

            Map<String, Object> payment_method = new Map<String, Object>();

            payment_method.put('name', name);

            payment_method.put('entry_mode', 'MOTO');

            payment_method.put('card', cardDetails);

            

            Map<String, Object> transaction_method = new Map<String, Object>();

            transaction_method.put('account_name', accountToPay);

            transaction_method.put('channel', 'CNP');

            transaction_method.put('type', 'SALE');

            transaction_method.put('capture_mode', 'AUTO');

            transaction_method.put('amount', String.ValueOf(amount));

            transaction_method.put('currency', 'GBP');

            String referenceTransaction = name;//first_name+''+last_name;

            if(referenceTransaction.length() > 32){

                referenceTransaction =  referenceTransaction.subString(0,32);

            }

            transaction_method.put('reference', referenceTransaction+''+reqrecord.opportunityId);

            transaction_method.put('country', 'GB');

            transaction_method.put('payment_method', payment_method);        

            String transactionBody = JSON.serialize(transaction_method);     

            

            HttpRequest req = new HttpRequest();

            req.setBody(transactionBody);

            req.setEndpoint(endPoint);

            req.setMethod('POST');

            req.setHeader('X-GP-Version', version);

            req.setHeader('Content-Type', 'application/json');

            req.setHeader('Authorization', 'Bearer ' + token);

            req.setTimeout(60000);

            Http http = new Http();

            HTTPResponse res = http.send(req);

            Map<String, Object> deserializedBody =  (Map<String,  Object>)JSON.deserializeUntyped(res.getBody());        

            String transactionId = String.ValueOf(deserializedBody.get('id'));  

            result.add(transactionId);

        }

        

        if(resetToken = true)

        {

            Globalpay_Auth__c authRecord = [select Token_Expire_Time__c, Token__c from Globalpay_Auth__c where Is_Sandbox__c =:orgType limit 1];  

            authRecord.Token_Expire_Time__c = tokenExpiredTime;

            authRecord.Token__c = token;

            update authRecord; 

        }

        return result;

    }




 

After running this code the response will look like this.

 

Get Transaction using API

Base url : https://apis.sandbox.globalpay.com

EndPoint : https://apis.sandbox.globalpay.com/ucp/transactions/{id

Method : GET

 

Header Parameters

authorization required string example: Bearer G3FA4TuYGCBiCWs4YpzrALGCYXZJ
x-gp-version required string example:2021-03-22
accept   string example: application/json

 

Query Parameters

id required string

 

Write below apex code to get a transaction using Rest API.

@AuraEnabled(cacheable=false)

    public static String getAuthCodeCodeFromTransaction(String transactionId)

    {

        String authCode = 'No Transaction Available';

        GlobalPaymentsService gp = new GlobalPaymentsService();

        HttpRequest req = new HttpRequest();

        String endPoint = endPointURL + '/ucp/transactions/' + transactionId;

        req.setEndpoint(endPoint);

        req.setMethod('GET');

        req.setHeader('X-GP-Version', version);    //'2021-03-22');

        req.setHeader('Content-Type', 'application/json');

        req.setHeader('Authorization', 'Bearer ' + token);

        req.setTimeout(60000);

        Http http = new Http();

        HTTPResponse res = http.send(req);

        Map<String, Object> deserializedBody =  (Map<String, Object>)JSON.deserializeUntyped(res.getBody()); 

        System.Debug(' deserializedBody ' + deserializedBody);

        String transactionStatus = String.ValueOf(deserializedBody.get('status'));

        //Check the status of transaction

        if(transactionStatus == 'CAPTURED')

        {

            Map<String, Object> payment_method =  (Map<String, Object>)deserializedBody.get('payment_method'); 

            Map<String, Object> card =  (Map<String, Object>)payment_method.get('card');

            authCode = String.valueOf(card.get('authcode'));    

        }

        return authCode;

    }

 

Response:

 

 

I hope this blog helped you!