# Webhook Controller

## Create a Controller Class

{% hint style="info" %}
In this example, the access tokens are managed with <mark style="color:blue;">JsonNode</mark> to make this sample as simple as possible.&#x20;

However, in your project for production system, you will need to manage the tokens using <mark style="color:red;">Entity</mark> and <mark style="color:red;">TokenRepository</mark> rather than <mark style="color:blue;">JsonNode</mark>.
{% endhint %}

{% code title="WebhookController.java" %}

```java
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
```

{% endcode %}

```java
@RestController
public class WebhookController {
	
 @Autowired
 private EformSignService eformSignService;
 
 public static JsonNode token;
 private static Map<String, Object> map = new HashMap<>();
 private static JsonNode res;
 private static String downPath = "C:\\Users\\Public\\Downloads\\";	
 private static String member_id = "john.kim@forcs.com";
 private static String fileType = "document,audit_trail";
 private static String apiUrl;
 private static String accessToken;
 private static String refreshToken;
 private static String expiredAt;
```

```java
@PostMapping(value = "/webhook")
public void postBody(
    @RequestHeader("eformsign_signature") String signature,
    @RequestBody String body) throws Exception {
    
    System.out.println("    Webhook Header: " + signature);
    System.out.println("              Body: " + body);
    
    boolean valid = EformSignService.verifySignature(signature, body);
    System.out.println("   verifySignature: " + valid);
    
    if (valid) {		
	JSONParser jsonParse = new JSONParser();
	JSONObject jsonObj = (JSONObject) jsonParse.parse(body);
	String event_type = (String) jsonObj.get("event_type");
	JSONObject doc = (JSONObject) jsonObj.get(event_type);
	String document_status = (String) doc.get("document_status");
 	
 	if(token == null) {
 	    res = eformSignService.getAccessToken(member_id).block();
 	    saveToken();
 	    System.out.println("    getAccessToken: " + token); 		
    	} else if ( System.currentTimeMillis() > token.get("expiredAt").asLong()) {
    	    System.out.println("     Token expired." );
    	    res = eformSignService.getRefreshToken(token).block();
    	    saveToken();
    	    System.out.println("   getRefreshToken: " + res);
    	}
	    	
	if(event_type.equals("ready_document_pdf") && document_status.equals("doc_complete")) {				
	    String documentId = (String) doc.get("document_id");
	    			    		   		
	    byte[] bytes = eformSignService.downloadDocument(token, documentId, fileType).block();
	    Path path = Paths.get( downPath + documentId + ".zip");
	    Files.write(path, bytes);
	    System.out.println("  downloadDocument: " + path.getFileName() + " (" + Files.size(path) + " bytes)");
		    		
	    res = eformSignService.deleteDocument(token, documentId).block();
	    System.out.println("    deleteDocument: " +  downPath+documentId+".zip" + res);
	}
     }
 }
```

```java
private static void saveToken() {	 
    try {
	apiUrl = res.get("api_key").get("company").get("api_url").asText();
    } catch (NullPointerException e) {}
    accessToken = res.get("oauth_token").get("access_token").asText();
    refreshToken = res.get("oauth_token").get("refresh_token").asText();
    int expiresIn = res.get("oauth_token").get("expires_in").asInt();
    expiredAt = (((new Date().getTime() + (expiresIn - 3580) * 1000L)) + "");

    if (apiUrl != null) map.put("apiUrl", apiUrl);
    map.put("accessToken", accessToken);
    map.put("refreshToken", refreshToken);
    map.put("expiredAt", expiredAt);

    ObjectMapper objectMapper = new ObjectMapper();
    token = objectMapper.valueToTree(map);	
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://efs.ozeform.io/sample-project/webhook-controller.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
