Integration Of Braintree Payment Gateway In Spring Boot
Posted By : Dharmendra Kumar | 31-May-2018
Nowadays Braintree is very popular payment gateway. It is full-stack payments platform to accept payment on your website or app.
All kind of organizations can use it to accept payment. It can accept payment from all over the world but for merchants, it's available in the limited country.
So as a merchant first you have to check whether Braintree available in your country or not.
It can acknowledge installment from PayPal, Apple Pay, Android Pay, Venmo, and most credit and platinum cards, including Visa, Mastercard, American Express, Discover, JCB, and Diner's Club.
1. To integrate Braintree payment gateway in your project, first of all, you have to add maven dependency in pom.xml
<dependency>
<groupId>com.braintreepayments.gateway</groupId>
<artifactId>braintree-java</artifactId>
<version>2.80.0</version>
</dependency>
2. Now go to below link and create your sandbox account for testing purpose.
https://sandbox.braintreegateway.com/
3. copy your API keys from Braintree dashboard.
4. run this command from your console:
5.paste your account info as shown below in bash.src, file and save it.
export BT_ENVIRONMENT="sandbox"
export BT_MERCHANT_ID="your merchant id"
export BT_PUBLIC_KEY="your public key"
export BT_PRIVATE_KEY="your private key"
6. run this command from console:source ~/.bashrc
7. Change your projects application class as shown below
@SpringBootApplication
public class AbcApplication {
@Autowired
private EnvConfiguration configuration;
private static final Logger LOGGER = LoggerFactory.getLogger(AbcApplication.class);
public static BraintreeGateway gateway;
public static void main(String[] args) {
LOGGER.debug("starting AbcApplication");
try {
gateway = BraintreeGatewayFactory.fromConfigMapping(System.getenv());
} catch (NullPointerException e) {
System.err.println("Could not load Braintree configuration from config file or system environment.");
System.exit(1);
}
SpringApplication.run(AbcApplication.class, args);
}
8.create a class file to initialize gateway object as
public class BraintreeGatewayFactory {
public static BraintreeGateway fromConfigMapping(Map<String, String> mapping) {
return new BraintreeGateway(mapping.get("BT_ENVIRONMENT"), mapping.get("BT_MERCHANT_ID"),
mapping.get("BT_PUBLIC_KEY"), mapping.get("BT_PRIVATE_KEY"));
}
}
9.Create a controller to create client token and perform payment
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
@Api(value = "Payment-controller", description = "Operation pertaining to Payment")
@RestController
@RequestMapping("/api/v1")
public class PaymentController {
private BraintreeGateway gateway = AbcApplication.gateway;
private static final Logger logger = LoggerFactory.getLogger(PaymentController.class);
@Autowired
private AuthTokenService authtokenservice;
@Autowired
private TransHistoryRepository transHistoryRepository;
/*
* @Description : Method is used to generate client token at the time of payment
* page loading.
*
* @Return : clientToken
*
*/
@Activity(methodType = com.starin.constants.RequestMethod.GET, url = "/client/token")
@ApiOperation(value = "generate token", response = ResponseEntity.class)
@RequestMapping(value = "/client/token", method = RequestMethod.GET, produces = {
MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<Object> generateClientToken() {
String clientToken = gateway.clientToken().generate();
return ResponseUtil.response(clientToken, MessageUtility.getSuccessMessage("tokencreated"), HttpStatus.CREATED);
}
/*
* @Description: Method is used to complete the transaction over payment gateway
*
* @param : paymentForm
*
* @Return: transaction details
*
*/
@Activity(methodType = com.starin.constants.RequestMethod.POST, url = "/payment/process")
@ApiOperation(value = "for payment", response = ResponseEntity.class)
@RequestMapping(value = "/payment/process", method = RequestMethod.POST)
public ResponseEntity<Object> processTransaction(
@RequestBody Payment paymentForm) {
Transaction transaction = null;
BigDecimal decimalAmount = null;
try {
decimalAmount = new BigDecimal(paymentForm.getChargeAmount());
} catch (NumberFormatException e) {
logger.info("NumberFormatException {}", e);
}
TransactionRequest request = new TransactionRequest().amount(decimalAmount)
.paymentMethodNonce(paymentForm.getNonce()).options().submitForSettlement(true).done();
Result<Transaction> result = gateway.transaction().sale(request);
logger.info("result.isSuccess() {}", result.isSuccess());
if (result.isSuccess() || result.getTransaction() != null) {
try {
transaction = result.getTarget();
transaction = gateway.transaction().find(transaction.getId());
} catch (Exception e) {
logger.info("Exception {}", e);
}
return ResponseUtil.response(transaction, result.getMessage(), HttpStatus.OK);
} else {
return ResponseUtil.errorResponse(result.getMessage(), HttpStatus.BAD_GATEWAY);
}
}
}
10.Create Payment domain as
public class Payment {
private String chargeAmount;
private String nonce;
/** * @return the chargeAmount */
public String getChargeAmount() {
return chargeAmount;
}
/** * @param chargeAmount * the chargeAmount to set */
public void setChargeAmount(String chargeAmount) {
this.chargeAmount = chargeAmount;
}
/** * @return the nonce */
public String getNonce() {
return nonce;
}
/** * @param nonce * the nonce to set */
public void setNonce(String nonce) {
this.nonce = nonce;
}
}
11. Now, first of all, you have to create client token by hitting generateClientToken() API from UI and then a payment form would open and after filling that form you have to hit processTransaction() API.
After performing all the above steps, our payment gateway would be integrated with Backend.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Dharmendra Kumar
Dharmendra is skilled in Java, Spring MVC, JPA, MySQL, and C.He has Bachelor's degree focussed in Computer Science and Engineering.