I am working on a mini e-commerce app with card payment integration also. User will add items to his/her cart as much as they want. Now there is another endpoint that performs the checkout order. This endpoint uses the logged in user’s email to retrieve all the items that the user has in his/her cart for the order to be placed. The implementation is that when the user perform the checkout, it will ask the user to select payment method either cash on delivery or online card payment. If the user select on cash on delivery, it will place the order and then store the order info into the database but if the user select on card payment, I only want to place the order if and only if the transaction is successful. I have implemented a paystack payment integration but the problem is how I can proceed to make the payment from here, verify it and then return to place the order after a successful payment.
@Override
public SaleServerResponse checkOut(SaleDto saleDto, HttpServletRequest request) {
UserEntity buyer = userService.findUserByEmail(saleDto.getBuyerEmail());
if (Objects.isNull(buyer)){
return new SaleServerResponse(baseUrl+request.getRequestURI(),"NOT OK",new SaleResponse(
406,"Buyer Verification","Provided buyer email not found",null
));
}
if (Objects.isNull(saleDto.getPaymentType())|| saleDto.getPaymentType().equalsIgnoreCase("")){
return new SaleServerResponse(baseUrl+request.getRequestURI(),"NOT OK",new SaleResponse(
406,"Payment method Verification","Please provide a payment method",null
));
}
SaleEntity sale = SaleEntity.builder()
.status("Pending Delivery")
.paymentType(saleDto.getPaymentType())
.datePurchased(new Date())
.deliveredPersonName(saleDto.getDeliveredPersonName())
.buyer(buyer)
.paymentStatus("Pending")
.deliveredAddress(saleDto.getDeliveredAddress())
.deliveredPhone(saleDto.getDeliveredPhone())
.totalPrice(getTotalAmount(buyer))
.cartItemList(getAllCartItemForTheBuyer(buyer))
.build();
if (getAllCartItemForTheBuyer(buyer).size()<1){
return new SaleServerResponse(baseUrl+request.getRequestURI(),"NOT OK",new SaleResponse(
406,"Checkout Verification","There is no item in your cart",null
));
}
//this is if the user want to pay on delivery
if (saleDto.getPaymentType().equalsIgnoreCase("Cash on Delivery")){
saleRepository.save(sale);
final OrderTokenEntity orderToken = new OrderTokenEntity(sale);
orderTokenService.saveOrderToken(orderToken);
updateCartItemCheckOutStatus(getAllCartItemForTheBuyer(buyer));
}else {
//This one will only proceed after a successful payment
//This is where I want to call my payment gateway implementation
//And later place the order if the payment was successful
}
return null;
}
@Override
public InitializePaymentResponse initializePayment(InitializePaymentDto initializePaymentDto) {
Map<String, String> request = new HashMap<>();
double amountToBePaid = initializePaymentDto.getAmount() * 100;
request.put("email", initializePaymentDto.getEmail());
request.put("amount", String.valueOf(amountToBePaid));
request.put("currency", initializePaymentDto.getCurrency());
ResponseEntity<InitializePaymentResponse> response = restTemplate.post(PAYSTACK_INITIALIZE_PAY, request, this.headers());
if (response.getStatusCode() == HttpStatus.OK) {
ObjectMapper objectMapper = new ObjectMapper();
Map<String, Object> mapResponse = objectMapper.convertValue(response.getBody().getData(), Map.class);
return InitializePaymentResponse.builder()
.message(response.getBody().getMessage())
.status(true)
.data(mapResponse)
.build();
}
return new InitializePaymentResponse(false,response.getBody().getMessage(),null);
}
@Override
@Transactional
public PaymentVerificationResponse paymentVerification(String reference, String plan,String email) throws Exception {
PaymentVerificationResponse paymentVerificationResponse = null;
SellerPaymentStack paymentPaystack = null;
try{
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(PAYSTACK_VERIFY + reference);
request.addHeader("Content-type", "application/json");
request.addHeader("Authorization", "Bearer " + payStackSecretKey);
StringBuilder result = new StringBuilder();
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == STATUS_CODE_OK) {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
} else {
return new PaymentVerificationResponse("Payment Verification failed",response.toString(),null);
}
ObjectMapper mapper = new ObjectMapper();
paymentVerificationResponse = mapper.readValue(result.toString(), PaymentVerificationResponse.class);
if (paymentVerificationResponse == null || paymentVerificationResponse.getStatus().equals("false")) {
throw new Exception("An error");
} else if (paymentVerificationResponse.getData().getStatus().equals("success")) {
SellerEntity seller = sellerRepository.findByEmail(email);
paymentPaystack = SellerPaymentStack.builder()
.seller(seller)
.reference(paymentVerificationResponse.getData().getReference())
.amount(paymentVerificationResponse.getData().getAmount())
.gatewayResponse(paymentVerificationResponse.getData().getGatewayResponse())
.paidAt(paymentVerificationResponse.getData().getPaidAt())
.createdAt(paymentVerificationResponse.getData().getCreatedAt())
.channel(paymentVerificationResponse.getData().getChannel())
.currency(paymentVerificationResponse.getData().getCurrency())
.ipAddress(paymentVerificationResponse.getData().getIpAddress())
.status(paymentVerificationResponse.getData().getStatus())
.createdOn(new Date())
.build();
}
} catch (Exception ex) {
throw new Exception("Paystack");
}
return paymentVerificationResponse;
}
private HttpHeaders headers() {
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer "+payStackSecretKey);
headers.set("Content-type", "application/json");
return headers;
}