How to implement webhook in spring webApplication.
Posted By : Ravindra Singh | 16-Sep-2018
Introduction :
The concept of webhook is very Simple, webhook is nothing but a simple HTTP callback. When something happens the HTTP POST call's the registered URL as a simple notification.
In other words, we talk about the Webhook is the concept that in Web Applications when certain things happen then automatic registered URL is called by HTTP POST to notify the users on the web application that your requested data status is changed please review it.
>>How to implement the webhook in spring Application, follow the below steps :
1.> First, we will create an API that will take the KYC information from users and then send this information to the Third Party Application by RestTemplate for verifying the user information and that third party return the Json Response to the user as KYC details submission.
UserKYCController class
package com.example.com.controller;
@Api
@RestController
@RequestMapping(value = UrlConstant.BASE_URI_V1)
public class UserKYCController {
private Logger logger = LoggerFactory.getLogger(UserKYCController.class);
@Autowired
private UserKYCService userKYCService;
/**
* @param userKYCInput
* @param result
* @return
*/
@RequestMapping(value = UrlConstant.UPLOAD_CONSUMER_KYC_DOCUMENT, method = RequestMethod.POST)
public ResponseEntity<Object> uploadKYCDetails(@Valid @RequestBody UserKYCInput userKYCInput,
BindingResult result) {
if (result.hasErrors()) {
return ResponseHandler.response(HttpStatus.BAD_REQUEST, true, ErrorCollectionUtil.getError(result),
ErrorCode.ERROR, Message("bad.request"),
ResponseCode.ACKNOWLEDGE_OPTIONAL_RESPONSE_OBJECT, ErrorCollectionUtil.getErrorMap(result));
}
ResponseEntity<String> response = userKYCService.sendUserKyc(userKYCInput);
if (response != null) {
return ResponseHandler.response(HttpStatus.OK, false, Message("user.KYC.save.success"),
ErrorCode.OK, ResponseCode.ACKNOWLEDGE, response);
} else {
genericUtil.saveData(userKYCInput);
return ResponseHandler.response(HttpStatus.INTERNAL_SERVER_ERROR, true,
Message("user.KYC.save.failure"), ErrorCode.ERROR,
ResponseCode.ACKNOWLEDGE_OPTIONAL_RESPONSE_OBJECT);
}
}
}
UserKYCServiceImpl class
package com.example.com.service.Userkyc;
@Service
public class UserKYCServiceImpl implements UserKYCService {
public static final Logger logger = LoggerFactory.getLogger(UserKYCServiceImpl.class);
@Autowired
private UserKYCRepository userKYCRepository;
@Value("${user.kyc.restTemplate.url}")
private String kycClientURL;
@Value("${user.kyc.restTemplate.authKey}")
private String kycAuthKey;
@Autowired
private UserService userService;
@Override
public ResponseEntity<String> sendUserKyc(UserKYCInput userKYCDetail) {
RestTemplate restTemplate = new RestTemplate();
String url = kycClientURL;
String base64Creds = kycAuthKey;
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<UserKYCInput> request = new HttpEntity<>(userKYCDetail, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
uploadUserKyc(userKYCDetail, response);
return response;
}
}
2.> second, we will create another API And this API URL is registered with That Third Party Application where the User KYC information was sent, When verification is successful, then third party will automatically call to our registered URL with updated Json Response or we can say User will automatically be notified by the Third party through calling this register URL so this URL is called as (Webhook URL).
UserKYCWebhookController class
package com.example.com.controller;
@Api
@RestController
@RequestMapping(value = UrlConstant.BASE_KYC_WEBHOOK_URI_V1)
public class UserKYCWebhookController {
private static final Logger logger = getLogger(UserKYCWebhookController.class);
@Autowired
private UserKYCService userKYCService;
@Autowired
private WebHookDetailsService webHookDetailsService;
@Autowired
private PasswordEncoderUtil passwordEncoderUtil;
/**
* @param notificationDto
* @param httpRequest
* @throws Exception
*/
@RequestMapping(value = UrlConstant.CONSUMER_KYC_WEBHOOK_NOTIFICATION_REQUEST, method = RequestMethod.POST)
public void getKYCWebhookData(@RequestBody Map<String, Object> notificationDto,HttpServletRequest httpRequest) {
final String authorization = httpRequest.getHeader("Authorization");
logger.debug("authorization {}", authorization);
if (authorization != null && authorization.startsWith("Basic")) {
String base64Credentials = authorization.substring("Basic".length()).trim();
String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
final String[] values = credentials.split(":", 2);
String userName = values[0].trim();
String password = values[1].trim();
WebHookDetails details = webHookDetailsService.getwebHookDetailsByUserName(userName);
if (Objects.nonNull(details)) {
String tid = notificationDto.get("tid").toString();
String state = notificationDto.get("state").toString();
Map<String, Object> response = new HashMap<>();
response.put("tid", tid);
response.put("state", state);
if (passwordEncoderUtil.matches(password, details.getPassword())) {
userKYCService.saveWebhookUpdatedResponse(response);
} else {
logger.debug("response == {}", false);
}
}
}
}
}
That's it all about webhook Implementation with spring web Application.
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
Ravindra Singh
Ravindra is Sr. Associate Consultant Development- Java (Backend Developer). And Familiar with AWS Cloud Machine Learning Programming (AWS Lex, Lambda, Polly, Elasticsearch ), And also having good experience in Spring Boot Microservice Architecture Applica