### Install Global Payments SDK via Maven
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Add this dependency to your pom.xml to include the Global Payments Java SDK from Maven Central.
```xml
com.globalpay
globalpayments-sdk
15.1.11
```
--------------------------------
### Process a Payment with Credit Card Details
Source: https://github.com/globalpayments/java-sdk/blob/master/README.md
Use this example to authorize a payment using credit card details. Ensure proper error handling for API exceptions.
```java
CreditCardData card = new CreditCardData();
card.setNumber("4111111111111111");
card.setExpMonth("12");
card.setExpYear("2025");
card.setCvn("123");
try
{
Transaction response = card.authorize(new BigDecimal("129.99"))
.withCurrency("EUR")
.execute();
String result = response.getResponseCode(); // 00 == Success
String message = response.getResponseMessage(); // [ test system ] AUTHORISED
}
catch (ApiException e)
{
// handle errors
}
```
--------------------------------
### Query Transactions and Disputes with ReportingService
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Use ReportingService to retrieve details for a single transaction or search transactions with pagination and filters. Also shows how to get dispute details.
```java
import com.global.api.entities.TransactionSummary;
import com.global.api.entities.reporting.*;
import com.global.api.services.ReportingService;
import com.global.api.entities.enums.TransactionStatus;
import org.joda.time.DateTime;
try {
// Get details for a single transaction
TransactionSummary txn = ReportingService
.transactionDetail("TRN_BHZ1whvNJnMvB6dPwf3znwWTsDposG")
.execute();
System.out.println("Amount: " + txn.getAmount() + ", Status: " + txn.getTransactionStatus());
// Search transactions paged with filters
TransactionSummaryPaged paged = ReportingService
.findTransactionsPaged(1, 10)
.orderBy(TransactionSortProperty.TimeCreated, SortDirection.Descending)
.where(SearchCriteria.TransactionStatus, TransactionStatus.Captured)
.and(SearchCriteria.StartDate, DateTime.now().minusDays(7))
.and(SearchCriteria.EndDate, DateTime.now())
.execute();
System.out.println("Total: " + paged.getTotalRecordCount());
for (TransactionSummary item : paged.getResults()) {
System.out.println(item.getTransactionId() + " - " + item.getAmount());
}
// Dispute detail
DisputeSummary dispute = ReportingService
.disputeDetail("DIS_SAND_abcd1234")
.execute();
System.out.println("Dispute status: " + dispute.getCaseStatus());
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### Void / Reverse a Transaction
Source: https://context7.com/globalpayments/java-sdk/llms.txt
This snippet shows how to reverse a previously authorized or settled transaction. It can be done using the original `Transaction` object or a `TransactionReference`. The example uses a static method `Transaction.fromId()` to initiate the reversal with a specified amount and currency.
```java
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.entities.Transaction;
import com.global.api.entities.TransactionReference;
import com.global.api.entities.enums.PaymentMethodType;
import java.math.BigDecimal;
// Using stored transaction reference
TransactionReference ref = new TransactionReference();
ref.setTransactionId("TXN-12345678");
ref.setPaymentMethodType(PaymentMethodType.Credit);
try {
// Reverse (void) using a reference
Transaction reversed = Transaction.fromId("TXN-12345678")
.reverse(new BigDecimal("49.99"))
.withCurrency("USD")
.execute();
System.out.println("Reversal: " + reversed.getResponseCode()); // "00"
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### Initialize Heartland with Callbacks
Source: https://github.com/globalpayments/java-sdk/blob/master/examples/end-to-end/index.html
Initializes the Heartland SDK and defines callback functions for token success, token errors, and general events. Use this to set up the payment processing flow.
```javascript
Heartland.init({
// ... other configurations
onTokenSuccess: function (resp) {
// create field and append to form
$("").attr({
type: "hidden",
id: "Token_value",
name: "Token_value",
value: resp.token_value
}).appendTo("#iframestoken");
// unbind event handler
$("#payment_form").unbind('submit');
// submit the form
$("#payment_form").submit();
},
onTokenError: function (resp) {
alert('There was an error: ' + resp.error.message);
},
onEvent: function (ev) {
console.log(ev);
}
});
```
--------------------------------
### Authorize Credit Card Funds (Pre-Authorization)
Source: https://context7.com/globalpayments/java-sdk/llms.txt
This snippet demonstrates how to authorize funds on a credit card without capturing them immediately. The authorization can be captured later using `ManagementBuilder.capture()`. Note the use of `withAllowDuplicates(true)` which may be necessary for certain testing scenarios.
```java
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.entities.Transaction;
import java.math.BigDecimal;
CreditCardData card = new CreditCardData();
card.setNumber("5425230000004415");
card.setExpMonth(12);
card.setExpYear(2025);
card.setCvn("123");
try {
// Step 1: Authorize
Transaction auth = card.authorize(new BigDecimal("100.00"))
.withCurrency("EUR")
.withAllowDuplicates(true)
.execute();
String authCode = auth.getAuthorizationCode(); // e.g. "123456"
String transId = auth.getTransactionId();
// Step 2: Capture (settle) later — optionally adjust amount
Transaction captured = auth.capture(new BigDecimal("95.00"))
.withGratuity(new BigDecimal("5.00"))
.execute();
System.out.println("Settled: " + captured.getResponseCode()); // "00"
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### Initiate Open Banking / Bank-to-Bank Transfer
Source: https://context7.com/globalpayments/java-sdk/llms.txt
This snippet shows how to initiate an open banking transaction, redirecting the customer to their bank for authorization. Ensure the correct bank payment type and return URLs are configured.
```java
import com.global.api.paymentMethods.BankPayment;
import com.global.api.entities.Transaction;
import com.global.api.entities.enums.BankPaymentType;
import java.math.BigDecimal;
BankPayment bankPayment = new BankPayment();
bankPayment.setAccountName("John Doe");
bankPayment.setAccountNumber("12345678");
bankPayment.setSortCode("406650");
bankPayment.setReturnUrl("https://example.com/return");
bankPayment.setStatusUpdateUrl("https://example.com/status");
bankPayment.setCancelUrl("https://example.com/cancel");
bankPayment.setBankPaymentType(BankPaymentType.FASTERPAYMENTS);
try {
Transaction response = bankPayment.charge(new BigDecimal("10.99"))
.withCurrency("GBP")
.withRemittanceReference(
RemittanceReferenceType.TEXT,
"Invoice 12345"
)
.execute();
// Redirect customer to the bank authorization URL
String redirectUrl = response.getBankPaymentResponse().getRedirectUrl();
System.out.println("Redirect to: " + redirectUrl);
System.out.println("OB transaction id: " + response.getTransactionId());
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### Simulate PIA Success Result
Source: https://github.com/globalpayments/java-sdk/blob/master/src/test/java/com/global/api/tests/terminals/upa/fileExamples/UDDataFile.html
This snippet demonstrates how to simulate a successful command result for PIA testing and display it on screen. Ensure the display object is available in the scope.
```javascript
var dataStr = JSON.stringify({ 'cmdResult': { 'result':'Success' } }); display.onScreenResult(dataStr);
```
--------------------------------
### Configure Portico Gateway Service (Legacy Credentials)
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Configure the Heartland Portico gateway using legacy credentials, including site ID, license ID, device ID, username, and password. This method is less preferred than using a secret API key.
```java
// OR using legacy credentials
PorticoConfig legacyConfig = new PorticoConfig();
legacyConfig.setSiteId(20518);
legacyConfig.setLicenseId(20527);
legacyConfig.setDeviceId(90911395);
legacyConfig.setUsername("777700004158");
legacyConfig.setPassword("$Test1234");
legacyConfig.setEnvironment(Environment.TEST);
try {
ServicesContainer.configureService(config);
} catch (ConfigurationException e) {
e.printStackTrace();
}
```
--------------------------------
### Perform 3D Secure v2 Authentication
Source: https://context7.com/globalpayments/java-sdk/llms.txt
This snippet demonstrates the complete 3D Secure v2 authentication flow, including checking enrollment, initiating authentication, and retrieving the final result. Ensure all necessary imports are included and handle potential API exceptions.
```java
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.entities.*;
import com.global.api.entities.enums.*;
import com.global.api.services.Secure3dService;
CreditCardData card = new CreditCardData();
card.setNumber("4263970000005262");
card.setExpMonth(12);
card.setExpYear(2025);
card.setCvn("123");
BrowserData browserData = new BrowserData();
browserData.setAcceptHeader("text/html,application/xhtml+xml");
browserData.setColorDepth(ColorDepth.TwentyFourBit);
browserData.setIpAddress("123.123.123.123");
browserData.setJavaEnabled(true);
browserData.setLanguage("en");
browserData.setScreenHeight(1080);
browserData.setScreenWidth(1920);
browserData.setUserAgent("Mozilla/5.0 ...");
try {
// Step 1: Check enrollment
ThreeDSecure enrolled = Secure3dService.checkEnrollment(card)
.withCurrency("USD")
.withAmount(new BigDecimal("100.00"))
.execute();
if (enrolled.isEnrolled()) {
// Step 2: Initiate authentication (returns ACS URL for cardholder challenge)
ThreeDSecure initiated = Secure3dService.initiateAuthentication(card, enrolled)
.withAmount(new BigDecimal("100.00"))
.withCurrency("USD")
.withBrowserData(browserData)
.withAuthenticationSource(AuthenticationSource.Browser)
.withMethodUrlCompletion(MethodUrlCompletion.Yes)
.execute();
// Redirect cardholder to initiated.getIssuerAcsUrl() for challenge ...
// Step 3: After challenge, get authentication data
ThreeDSecure authData = Secure3dService.getAuthenticationData()
.withServerTransactionId(initiated.getServerTransactionId())
.execute();
card.setThreeDSecure(authData);
// Step 4: Charge with 3DS data attached
Transaction response = card.charge(new BigDecimal("100.00"))
.withCurrency("USD")
.execute();
System.out.println("3DS charge: " + response.getResponseCode());
}
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### Configure GP-Ecom Gateway Service
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Configure the Global Payments ecommerce gateway, including merchant credentials and optional 3DS v2 notification URLs. Ensure the correct environment and secure3d version are set.
```java
import com.global.api.serviceConfigs.GpEcomConfig;
import com.global.api.entities.enums.Environment;
import com.global.api.entities.enums.Secure3dVersion;
GpEcomConfig config = new GpEcomConfig();
config.setMerchantId("heartlandgpsandbox");
config.setAccountId("api");
config.setSharedSecret("secret");
config.setChannel("internet");
config.setEnvironment(Environment.TEST);
config.setSecure3dVersion(Secure3dVersion.TWO);
config.setMethodNotificationUrl("https://example.com/method-notification");
config.setChallengeNotificationUrl("https://example.com/challenge-notification");
try {
ServicesContainer.configureService(config);
} catch (ConfigurationException e) {
e.printStackTrace();
}
```
--------------------------------
### Configure GP-API Gateway
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Register a GP-API gateway configuration with the ServicesContainer. This can be done once at application startup and supports named configurations.
```APIDOC
## ServicesContainer.configureService — Configure the GP-API Gateway
Register a gateway configuration once at application startup. All subsequent API calls use the registered connector by name (or "default").
```java
import com.global.api.ServicesContainer;
import com.global.api.entities.enums.Channel;
import com.global.api.entities.enums.Environment;
import com.global.api.serviceConfigs.GpApiConfig;
GpApiConfig config = new GpApiConfig();
config.setAppId("OWTP5ptQZKGj7EnvPt3uqO844XDBt8Oj");
config.setAppKey("abcDefgHijkLmn12");
config.setChannel(Channel.CardNotPresent);
config.setEnvironment(Environment.TEST);
config.setCountry("US");
try {
ServicesContainer.configureService(config); // registers as "default"
ServicesContainer.configureService(config, "myGpApi"); // named config
} catch (ConfigurationException e) {
// Missing appId/appKey or invalid combination
e.printStackTrace();
}
```
```
--------------------------------
### Process Credit Card Sale (Authorization + Capture)
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Use this method to perform a full sale, which includes both authorization and auto-capture of funds. Ensure all required fields like card number, expiry, and amount are correctly provided. Handles potential API exceptions.
```java
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.entities.Address;
import com.global.api.entities.Transaction;
import com.global.api.entities.exceptions.ApiException;
import java.math.BigDecimal;
CreditCardData card = new CreditCardData();
card.setNumber("4263970000005262");
card.setExpMonth(12);
card.setExpYear(2025);
card.setCvn("123");
card.setCardHolderName("John Smith");
Address billingAddress = new Address();
billingAddress.setStreetAddress1("123 Main St");
billingAddress.setPostalCode("12345");
try {
Transaction response = card.charge(new BigDecimal("49.99"))
.withCurrency("USD")
.withAddress(billingAddress)
.withClientTransactionId("ORDER-20240101-001")
.execute();
String responseCode = response.getResponseCode(); // "00" = approved
String responseMsg = response.getResponseMessage(); // e.g. "[ test system ] AUTHORISED"
String transactionId = response.getTransactionId();
if ("00".equals(responseCode)) {
System.out.println("Payment approved: " + transactionId);
}
} catch (BuilderException e) {
// Invalid builder state (e.g., negative amount)
} catch (GatewayException e) {
// Gateway-level error or declined
} catch (ApiException e) {
// All other SDK errors
}
```
--------------------------------
### Build and Parse Hosted Payment Page (HPP) Request
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Use this snippet to build a hosted payment form request and parse the gateway response after a cardholder submits payment details on the hosted page. Ensure the necessary configurations for GpEcomConfig are set up.
```java
import com.global.api.services.HostedService;
import com.global.api.serviceConfigs.GpEcomConfig;
import com.global.api.serviceConfigs.HostedPaymentConfig;
import com.global.api.entities.Transaction;
import com.global.api.entities.enums.HppVersion;
import java.math.BigDecimal;
GpEcomConfig config = new GpEcomConfig();
config.setMerchantId("heartlandgpsandbox");
config.setAccountId("hpp");
config.setSharedSecret("secret");
config.setEnvironment(Environment.TEST);
config.setHostedPaymentConfig(new HostedPaymentConfig()
.setVersion(HppVersion.Version2)
.setResponseUrl("https://example.com/response"));
try {
HostedService service = new HostedService(config);
// Build the HPP charge request (returns JSON to embed in HTML form)
String hppJson = service.charge(new BigDecimal("19.99"))
.withCurrency("EUR")
.withOrderId("ORD-001")
.withClientTransactionId("CLIENT-001")
.serialize();
// Embed hppJson in frontend HTML to redirect to hosted page...
// Parse the response from the gateway's POST-back
String gatewayResponseJson = "... received from gateway POST-back ...";
Transaction response = service.parseResponse(gatewayResponseJson, true);
System.out.println("HPP result: " + response.getResponseCode());
System.out.println("Auth code: " + response.getAuthorizationCode());
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### Configure GP-Ecom Gateway
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Configure the Global Payments ecommerce gateway, including merchant credentials and optional 3DS v2 URLs.
```APIDOC
## GpEcomConfig — Configure the GP-Ecom Gateway
Configure the Global Payments ecommerce gateway with merchant credentials and optional 3DS v2 URLs.
```java
import com.global.api.serviceConfigs.GpEcomConfig;
import com.global.api.entities.enums.Environment;
import com.global.api.entities.enums.Secure3dVersion;
GpEcomConfig config = new GpEcomConfig();
config.setMerchantId("heartlandgpsandbox");
config.setAccountId("api");
config.setSharedSecret("secret");
config.setChannel("internet");
config.setEnvironment(Environment.TEST);
config.setSecure3dVersion(Secure3dVersion.TWO);
config.setMethodNotificationUrl("https://example.com/method-notification");
config.setChallengeNotificationUrl("https://example.com/challenge-notification");
try {
ServicesContainer.configureService(config);
} catch (ConfigurationException e) {
e.printStackTrace();
}
```
```
--------------------------------
### Handle Various Exceptions During Transaction Processing
Source: https://github.com/globalpayments/java-sdk/blob/master/README.md
This code demonstrates how to catch and handle different types of exceptions that may occur during payment processing, including builder, configuration, gateway, and general API errors.
```java
try
{
Transaction response = card.authorize(new BigDecimal("-5.00"))
.withCurrency("EUR")
.withAddress(address)
.execute();
}
catch (BuilderException e)
{
// handle builder errors
}
catch (ConfigurationException e)
{
// handle errors related to your services configuration
}
catch (GatewayException e)
{
// handle gateway errors/exceptions
}
catch (UnsupportedTransactionException e)
{
// handle errors when the configured gateway doesn't support
// desired transaction
}
catch (ApiException e)
{
// handle all other errors
}
```
--------------------------------
### Configure GP-API Gateway Service
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Register a GP-API gateway configuration with the ServicesContainer at application startup. This can be a default configuration or named for specific use.
```java
import com.global.api.ServicesContainer;
import com.global.api.entities.enums.Channel;
import com.global.api.entities.enums.Environment;
import com.global.api.serviceConfigs.GpApiConfig;
GpApiConfig config = new GpApiConfig();
config.setAppId("OWTP5ptQZKGj7EnvPt3uqO844XDBt8Oj");
config.setAppKey("abcDefgHijkLmn12");
config.setChannel(Channel.CardNotPresent);
config.setEnvironment(Environment.TEST);
config.setCountry("US");
try {
ServicesContainer.configureService(config); // registers as "default"
ServicesContainer.configureService(config, "myGpApi"); // named config
} catch (ConfigurationException e) {
// Missing appId/appKey or invalid combination
e.printStackTrace();
}
```
--------------------------------
### Initialize Heartland HPS with Iframe Configuration
Source: https://github.com/globalpayments/java-sdk/blob/master/examples/end-to-end/index.html
Configure the Heartland HPS object to use iframes for sensitive card details. Specify target elements for card number, expiration, CVV, and submit button. Includes CSS for styling the iframe fields to match the site's appearance.
```javascript
(function (document, Heartland) {
// Create a new `HPS` object with the necessary configuration
var hps = new Heartland.HPS({
publicKey: 'pkapi_cert_P6dRqs1LzfWJ6HgGVZ',
type: 'iframe',
// Configure the iframe fields to tell the library where
// the iframe should be inserted into the DOM and some
// basic options
fields: {
cardNumber: {
target: 'iframesCardNumber',
placeholder: '•••• •••• •••• ••••'
},
cardExpiration: {
target: 'iframesCardExpiration',
placeholder: 'MM / YYYY'
},
cardCvv: {
target: 'iframesCardCvv',
placeholder: 'CVV'
},
submit: {
target: 'iframesSubmit'
}
},
// Collection of CSS to inject into the iframes.
// These properties can match the site's styles
// to create a seamless experience.
style: {
'input': {
'background': '#fff',
'border': '1px solid',
'border-color': '#bbb3b9 #c7c1c6 #c7c1c6',
'box-sizing': 'border-box',
'font-family': 'serif',
'font-size': '16px',
'line-height': '1',
'margin': '0 .5em 0 0',
'max-width': '100%',
'outline': '0',
'padding': '0.5278em',
'vertical-align': 'baseline',
'height': '50px',
'width': '100% !important'
},
'#heartland-field': {
'font-family': 'sans-serif',
'box-sizing': 'border-box',
'display': 'block',
'height': '50px',
'padding': '6px 12px',
'font-size': '14px',
'line-height': '1.42857143',
'color': '#555',
'background-color': '#fff',
'border': '1px solid #ccc',
'border-radius': '0px',
'-webkit-box-shadow': 'inset 0 1px 1px rgba(0,0,0,.075)',
'box-shadow': 'inset 0 1px 1px rgba(0,0,0,.075)',
'-webkit-transition': 'border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s',
'-o-transition': 'border-color ease-in-out .15s,box-shadow ease-in-out .15s',
'transition': 'border-color ease-in-out .15s,box-shadow ease-in-out .15s',
'width': '100%'
},
'#heartland-field[name=submit]': {
'background-color': '#36b46e',
'font-family': 'sans-serif',
'text-transform': 'uppercase',
'color': '#ffffff',
'border': '0px solid transparent'
},
'#heartland-field[name=submit]:focus': {
'color': '#ffffff',
'background-color': '#258851',
'outline': 'none'
},
'#heartland-field[name=submit]:hover': {
'background-color': '#258851'
},
'#heartland-field-wrapper #heartland-field:focus': {
'border': '1px solid #3989e3',
'outline': 'none',
'box-shadow': 'none',
'height': '50px'
},
'heartland-field-wrapper #heartland-field': {
'height': '50px'
},
'input[type=submit]': {
'box-sizing': 'border-box',
'display': 'inline-block',
'padding': '6px 12px',
'margin-bottom': '0',
'font-size': '14px',
'font-weight': '400',
'line-height': '1.42857143',
'text-align': 'center',
'white-space': 'nowrap',
'vertical-align': 'middle',
'-ms-touch-action': 'manipulation',
'touch-action': 'manipulation',
'cursor': 'pointer',
'-webkit-user-select': 'none',
'-moz-user-select': 'none',
'-ms-user-select': 'none',
'user-select': 'none',
'background-image': 'none',
'border': '1px solid transparent',
'border-radius': '4px',
'color': '#fff',
'background-color': '#337ab7',
'border-color': '#2e6da4'
},
'#heartland-field[placeholder]': {
'letter-spacing': '3px'
},
'#heartland-field[name=cardCvv]': {
'background': 'transparent url(https://github.com/hps/heartland-php/blob/master/examples/end-to-end/assets/images/cvv1.png?raw=true) no-repeat right',
'background-size': '63px 40px'
},
'input#heartland-field[name=cardNumber]': {
'background': 'transparent url(https://github.com/hps/heartland-php/blob/master/examples/end-to-end/assets/images/ss-inputcard-blank@2x.png?raw=true) no-repeat right',
'background-size': '55px 35px'
},
'#heartland-field.invalid.card-type-visa': {
'background': 'transparent url(https://github.com/hps/heartland-php/blob/master/examples/end-to-end/assets/images/ss-saved-visa@2x.png?raw=true) no-repeat right',
'background-size': '83px 88px',
'background-position-y': '-44px'
},
'#heartland-field.valid.card-type-visa': {
'background': 'transparent url(https://github.com/hps/heartland-php/blob/master/examples/end-to-end/assets/images/ss-saved-visa@2x.png?raw=true) no-repeat right top',
'background-size': '82px 86px'
},
'#heartland-field.invalid.card-type-discover': {
'background': 'transparent url(https://github.com/hps/heartland-php/blob/master/examples/end-to-end/assets/images/ss-saved-discover@2x.png?raw=true) no-repeat right',
'background-size': '85px 90px',
'backgro'
}
}
});
})(document, Heartland);
```
--------------------------------
### Issue Standalone Credit / Refund
Source: https://context7.com/globalpayments/java-sdk/llms.txt
This code performs a standalone refund to a credit card. It does not require a prior transaction reference. Ensure the currency and amount are correctly specified. The `withAllowDuplicates(true)` option is included, which might be relevant for specific refund scenarios.
```java
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.entities.Transaction;
import java.math.BigDecimal;
CreditCardData card = new CreditCardData();
card.setNumber("4263970000005262");
card.setExpMonth(12);
card.setExpYear(2025);
try {
Transaction refund = card.refund(new BigDecimal("25.00"))
.withCurrency("USD")
.withAllowDuplicates(true)
.execute();
System.out.println("Refund response: " + refund.getResponseCode()); // "00"
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### Store Payment Method for Recurring Billing
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Store a customer and their payment method for subscription or recurring billing. First, create a customer record, then add and create the payment method associated with that customer.
```java
import com.global.api.entities.Customer;
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.paymentMethods.RecurringPaymentMethod;
import com.global.api.entities.Transaction;
import java.math.BigDecimal;
// Create a customer record
Customer customer = new Customer();
customer.setId("customer-" + System.currentTimeMillis());
customer.setFirstName("John");
customer.setLastName("Doe");
customer.setEmail("john.doe@example.com");
try {
Customer savedCustomer = customer.create();
// Store a payment method on the customer
CreditCardData card = new CreditCardData();
card.setNumber("4263970000005262");
card.setExpMonth(12);
card.setExpYear(2025);
card.setCvn("123");
RecurringPaymentMethod pm = savedCustomer.addPaymentMethod("PM001", card);
RecurringPaymentMethod savedPm = pm.create();
// Later: charge the stored payment method
Transaction response = new RecurringPaymentMethod(savedCustomer.getId(), savedPm.getKey())
.charge(new BigDecimal("29.99"))
.withCurrency("USD")
.execute();
System.out.println("Recurring charge: " + response.getResponseCode()); // "00"
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### Configure Portico Gateway Service (API Key)
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Configure the Heartland Portico gateway using a secret API key. This is the preferred method for authentication.
```java
import com.global.api.serviceConfigs.PorticoConfig;
import com.global.api.entities.enums.Environment;
// Using secret API key (preferred)
PorticoConfig config = new PorticoConfig();
config.setSecretApiKey("skapi_cert_MTyMAQBiHVEAewvIzXVFcmUd2UcyBge_eCpaASUp0A");
config.setEnvironment(Environment.TEST);
```
--------------------------------
### Secure3dService — 3D Secure v2 Authentication
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Perform 3DS2 enrollment check, initiate authentication, and retrieve the final authentication result. This process involves checking enrollment, initiating the authentication flow, and then retrieving the authentication data to complete a charge.
```APIDOC
## Secure3dService — 3D Secure v2 Authentication
Perform 3DS2 enrollment check, initiate authentication, and retrieve the final authentication result.
```java
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.entities.*;
import com.global.api.entities.enums.*;
import com.global.api.services.Secure3dService;
CreditCardData card = new CreditCardData();
card.setNumber("4263970000005262");
card.setExpMonth(12);
card.setExpYear(2025);
card.setCvn("123");
BrowserData browserData = new BrowserData();
browserData.setAcceptHeader("text/html,application/xhtml+xml");
browserData.setColorDepth(ColorDepth.TwentyFourBit);
browserData.setIpAddress("123.123.123.123");
browserData.setJavaEnabled(true);
browserData.setLanguage("en");
browserData.setScreenHeight(1080);
browserData.setScreenWidth(1920);
browserData.setUserAgent("Mozilla/5.0 ...");
try {
// Step 1: Check enrollment
ThreeDSecure enrolled = Secure3dService.checkEnrollment(card)
.withCurrency("USD")
.withAmount(new BigDecimal("100.00"))
.execute();
if (enrolled.isEnrolled()) {
// Step 2: Initiate authentication (returns ACS URL for cardholder challenge)
ThreeDSecure initiated = Secure3dService.initiateAuthentication(card, enrolled)
.withAmount(new BigDecimal("100.00"))
.withCurrency("USD")
.withBrowserData(browserData)
.withAuthenticationSource(AuthenticationSource.Browser)
.withMethodUrlCompletion(MethodUrlCompletion.Yes)
.execute();
// Redirect cardholder to initiated.getIssuerAcsUrl() for challenge ...
// Step 3: After challenge, get authentication data
ThreeDSecure authData = Secure3dService.getAuthenticationData()
.withServerTransactionId(initiated.getServerTransactionId())
.execute();
card.setThreeDSecure(authData);
// Step 4: Charge with 3DS data attached
Transaction response = card.charge(new BigDecimal("100.00"))
.withCurrency("USD")
.execute();
System.out.println("3DS charge: " + response.getResponseCode());
}
} catch (ApiException e) {
e.printStackTrace();
}
```
```
--------------------------------
### Configure Portico Gateway
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Configure the Heartland Portico gateway using either a secret API key or legacy site/license/device credentials.
```APIDOC
## PorticoConfig — Configure the Heartland Portico Gateway
Configure the Heartland Portico gateway using either a secret API key or legacy site/license/device credentials.
```java
import com.global.api.serviceConfigs.PorticoConfig;
import com.global.api.entities.enums.Environment;
// Using secret API key (preferred)
PorticoConfig config = new PorticoConfig();
config.setSecretApiKey("skapi_cert_MTyMAQBiHVEAewvIzXVFcmUd2UcyBge_eCpaASUp0A");
config.setEnvironment(Environment.TEST);
// OR using legacy credentials
PorticoConfig legacyConfig = new PorticoConfig();
legacyConfig.setSiteId(20518);
legacyConfig.setLicenseId(20527);
legacyConfig.setDeviceId(90911395);
legacyConfig.setUsername("777700004158");
legacyConfig.setPassword("$Test1234");
legacyConfig.setEnvironment(Environment.TEST);
try {
ServicesContainer.configureService(config);
} catch (ConfigurationException e) {
e.printStackTrace();
}
```
```
--------------------------------
### Assess Payment Method Risk with FraudService
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Submit a payment method for standalone risk assessment before charging using the GP-API fraud rules engine. Requires payment method details, amount, currency, billing address, and customer IP.
```java
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.entities.RiskAssessment;
import com.global.api.entities.Address;
import com.global.api.services.FraudService;
import java.math.BigDecimal;
CreditCardData card = new CreditCardData();
card.setNumber("4263970000005262");
card.setExpMonth(12);
card.setExpYear(2025);
Address billingAddress = new Address();
billingAddress.setStreetAddress1("123 Main St");
billingAddress.setPostalCode("12345");
billingAddress.setCountry("US");
try {
RiskAssessment result = FraudService.RiskAssess(card)
.withAmount(new BigDecimal("250.00"))
.withCurrency("USD")
.withBillingAddress(billingAddress)
.withCustomerIpAddress("123.123.123.123")
.execute();
System.out.println("Risk result: " + result.getResult()); // e.g. "ACCEPTED"
System.out.println("Score: " + result.getScore());
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### Add Global Payments Java SDK Dependency via Maven
Source: https://github.com/globalpayments/java-sdk/blob/master/README.md
Include this dependency in your Maven project to use the Global Payments Java SDK. Ensure you use the appropriate version for your project.
```xml
com.heartlandpaymentsystems
globalpayments-sdk
1.4-SNAPSHOT
```
--------------------------------
### RecurringPaymentMethod
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Store customer and payment method details for subscription or recurring billing using the PayPlan/GP-API vault.
```APIDOC
## RecurringPaymentMethod — Stored Card for Recurring Billing
Store a customer and payment method for subscription or recurring billing using the PayPlan/GP-API vault.
```java
import com.global.api.entities.Customer;
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.paymentMethods.RecurringPaymentMethod;
import com.global.api.entities.Transaction;
import java.math.BigDecimal;
// Create a customer record
Customer customer = new Customer();
customer.setId("customer-" + System.currentTimeMillis());
customer.setFirstName("John");
customer.setLastName("Doe");
customer.setEmail("john.doe@example.com");
try {
Customer savedCustomer = customer.create();
// Store a payment method on the customer
CreditCardData card = new CreditCardData();
card.setNumber("4263970000005262");
card.setExpMonth(12);
card.setExpYear(2025);
card.setCvn("123");
RecurringPaymentMethod pm = savedCustomer.addPaymentMethod("PM001", card);
RecurringPaymentMethod savedPm = pm.create();
// Later: charge the stored payment method
Transaction response = new RecurringPaymentMethod(savedCustomer.getId(), savedPm.getKey())
.charge(new BigDecimal("29.99"))
.withCurrency("USD")
.execute();
System.out.println("Recurring charge: " + response.getResponseCode()); // "00"
} catch (ApiException e) {
e.printStackTrace();
}
```
```
--------------------------------
### Tokenize Credit Card for Future Charges
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Store a card securely to obtain a token for future charges, avoiding PCI scope for card data storage. Use the token to create a new CreditCardData object for subsequent transactions.
```java
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.entities.exceptions.ApiException;
CreditCardData card = new CreditCardData();
card.setNumber("4263970000005262");
card.setExpMonth(12);
card.setExpYear(2025);
card.setCvn("123");
try {
// Tokenize and get the token string
String token = card.tokenize();
System.out.println("Token: " + token); // e.g. "5ab9726d-67ff-4c0c-b387-..."
// Later: charge using the token
CreditCardData tokenCard = new CreditCardData(token);
tokenCard.charge(new BigDecimal("19.99"))
.withCurrency("USD")
.execute();
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### HostedService — Hosted Payment Page (HPP)
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Build a hosted payment form request and parse the gateway response after the cardholder submits payment details on the hosted page.
```APIDOC
## HostedService — Hosted Payment Page (HPP)
### Description
Build a hosted payment form request and parse the gateway response after the cardholder submits payment details on the hosted page.
### Method
```java
// Example usage of HostedService
import com.global.api.services.HostedService;
import com.global.api.serviceConfigs.GpEcomConfig;
import com.global.api.serviceConfigs.HostedPaymentConfig;
import com.global.api.entities.Transaction;
import com.global.api.entities.enums.HppVersion;
import java.math.BigDecimal;
GpEcomConfig config = new GpEcomConfig();
config.setMerchantId("heartlandgpsandbox");
config.setAccountId("hpp");
config.setSharedSecret("secret");
config.setEnvironment(Environment.TEST);
config.setHostedPaymentConfig(new HostedPaymentConfig()
.setVersion(HppVersion.Version2)
.setResponseUrl("https://example.com/response"));
try {
HostedService service = new HostedService(config);
// Build the HPP charge request (returns JSON to embed in HTML form)
String hppJson = service.charge(new BigDecimal("19.99"))
.withCurrency("EUR")
.withOrderId("ORD-001")
.withClientTransactionId("CLIENT-001")
.serialize();
// Embed hppJson in frontend HTML to redirect to hosted page...
// Parse the response from the gateway's POST-back
String gatewayResponseJson = "... received from gateway POST-back ...";
Transaction response = service.parseResponse(gatewayResponseJson, true);
System.out.println("HPP result: " + response.getResponseCode());
System.out.println("Auth code: " + response.getAuthorizationCode());
} catch (ApiException e) {
e.printStackTrace();
}
```
```
--------------------------------
### Handle Form Submission for Tokenization
Source: https://github.com/globalpayments/java-sdk/blob/master/examples/end-to-end/index.html
Attaches an event handler to the form's submit event to prevent default submission and initiate the tokenization process. This is crucial for securely capturing payment details.
```javascript
Heartland.Events.addHandler(document.getElementById('iframes'), 'submit', function (e) {
// Prevent the form from continuing to the `action` address
e.preventDefault();
// Tell the iframes to tokenize the data
hps.Messages.post({
accumulateData: true,
action: 'tokenize',
message: 'pkapi_cert_P6dRqs1LzfWJ6HgGVZ'
}, 'cardNumber');
});
```
--------------------------------
### Close Settlement Batch with BatchService
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Close the current open batch for card-present or network integrations to trigger settlement. Supports simple batch closure and forced closure with specified totals.
```java
import com.global.api.entities.BatchSummary;
import com.global.api.entities.enums.BatchCloseType;
import com.global.api.services.BatchService;
try {
// Simple batch close
BatchSummary summary = BatchService.closeBatch();
System.out.println("Batch closed: " + summary.getBatchId());
System.out.println("Transaction count: " + summary.getTransactionCount());
System.out.println("Total amount: " + summary.getTotalAmount());
// Forced batch close with totals
BatchSummary manual = BatchService
.closeBatch(BatchCloseType.Forced, 42, 10, new BigDecimal("500.00"), new BigDecimal("50.00"))
.execute()
.getBatchSummary();
} catch (ApiException e) {
e.printStackTrace();
}
```
--------------------------------
### Generate GP-API Access Token
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Use this snippet to generate a standalone GP-API access token for front-end or client-side integrations. Ensure the GpApiConfig is correctly set with your application's credentials and environment details.
```java
import com.global.api.entities.enums.Channel;
import com.global.api.entities.enums.Environment;
import com.global.api.entities.gpApi.entities.AccessTokenInfo;
import com.global.api.serviceConfigs.GpApiConfig;
import com.global.api.services.GpApiService;
GpApiConfig config = new GpApiConfig();
config.setAppId("OWTP5ptQZKGj7EnvPt3uqO844XDBt8Oj");
config.setAppKey("abcDefgHijkLmn12");
config.setChannel(Channel.CardNotPresent);
config.setEnvironment(Environment.TEST);
config.setSecondsToExpire(900); // 15 minutes
try {
AccessTokenInfo tokenInfo = GpApiService.generateTransactionKey(config);
System.out.println("Token: " + tokenInfo.getAccessToken());
System.out.println("Txn Acct: " + tokenInfo.getTransactionProcessingAccountName());
} catch (GatewayException e) {
e.printStackTrace();
}
```
--------------------------------
### GpApiService.generateTransactionKey — Obtain a GP-API Access Token
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Generate a standalone GP-API access token for use in front-end / client-side integrations.
```APIDOC
## GpApiService.generateTransactionKey — Obtain a GP-API Access Token
### Description
Generate a standalone GP-API access token for use in front-end / client-side integrations.
### Method
```java
import com.global.api.entities.enums.Channel;
import com.global.api.entities.enums.Environment;
import com.global.api.entities.gpApi.entities.AccessTokenInfo;
import com.global.api.serviceConfigs.GpApiConfig;
import com.global.api.services.GpApiService;
GpApiConfig config = new GpApiConfig();
config.setAppId("OWTP5ptQZKGj7EnvPt3uqO844XDBt8Oj");
config.setAppKey("abcDefgHijkLmn12");
config.setChannel(Channel.CardNotPresent);
config.setEnvironment(Environment.TEST);
config.setSecondsToExpire(900); // 15 minutes
try {
AccessTokenInfo tokenInfo = GpApiService.generateTransactionKey(config);
System.out.println("Token: " + tokenInfo.getAccessToken());
System.out.println("Txn Acct: " + tokenInfo.getTransactionProcessingAccountName());
} catch (GatewayException e) {
e.printStackTrace();
}
```
```
--------------------------------
### CreditCardData.charge
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Processes a full credit card sale, including authorization and auto-capture. It returns a Transaction object with the response details.
```APIDOC
## CreditCardData.charge — Process a Credit Card Sale
Perform a full sale (authorization + auto-capture) against a credit card. Returns a `Transaction` object containing the response code and message.
```java
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.entities.Address;
import com.global.api.entities.Transaction;
import com.global.api.entities.exceptions.ApiException;
import java.math.BigDecimal;
CreditCardData card = new CreditCardData();
card.setNumber("4263970000005262");
card.setExpMonth(12);
card.setExpYear(2025);
card.setCvn("123");
card.setCardHolderName("John Smith");
Address billingAddress = new Address();
billingAddress.setStreetAddress1("123 Main St");
billingAddress.setPostalCode("12345");
try {
Transaction response = card.charge(new BigDecimal("49.99"))
.withCurrency("USD")
.withAddress(billingAddress)
.withClientTransactionId("ORDER-20240101-001")
.execute();
String responseCode = response.getResponseCode(); // "00" = approved
String responseMsg = response.getResponseMessage(); // e.g. "[ test system ] AUTHORISED"
String transactionId = response.getTransactionId();
if ("00".equals(responseCode)) {
System.out.println("Payment approved: " + transactionId);
}
} catch (BuilderException e) {
// Invalid builder state (e.g., negative amount)
} catch (GatewayException e) {
// Gateway-level error or declined
} catch (ApiException e) {
// All other SDK errors
}
```
```
--------------------------------
### CreditCardData.tokenize
Source: https://context7.com/globalpayments/java-sdk/llms.txt
Tokenize a credit card to securely store card details and obtain a token for future transactions, reducing PCI scope.
```APIDOC
## CreditCardData.tokenize — Tokenize a Card
Store a card securely and obtain a token for future charges, avoiding PCI scope for card data storage.
```java
import com.global.api.paymentMethods.CreditCardData;
import com.global.api.entities.exceptions.ApiException;
CreditCardData card = new CreditCardData();
card.setNumber("4263970000005262");
card.setExpMonth(12);
card.setExpYear(2025);
card.setCvn("123");
try {
// Tokenize and get the token string
String token = card.tokenize();
System.out.println("Token: " + token); // e.g. "5ab9726d-67ff-4c0c-b387-..."
// Later: charge using the token
CreditCardData tokenCard = new CreditCardData(token);
tokenCard.charge(new BigDecimal("19.99"))
.withCurrency("USD")
.execute();
} catch (ApiException e) {
e.printStackTrace();
}
```
```