Skip to content

Commit

Permalink
update lib, add webhook endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
kocherovv committed Dec 4, 2023
1 parent 0b6a4a4 commit 1ddb967
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 33 deletions.
29 changes: 18 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,25 @@ sudo ufw enable

### Import

Install the library into your server project. The library is available in the Maven central repository.

Maven
```xml
<dependency>
<groupId>com.green-api</groupId>
<artifactId>whatsapp-api-webhook-server-java</artifactId>
<version>{{version}}</version>
<groupId>com.green-api</groupId>
<artifactId>whatsapp-api-webhook-server-java</artifactId>
<version>{{version}}</version>
</dependency>
```

Gradle
```yaml
implementation group: 'com.green-api', name: 'whatsapp-api-client-java', version: 'version'
```
### Examples
#### How to initialize an object
#### How to run the web server
Set server options in `application.yml`.
The WebhookToken attribute is optional and does not need to be assigned a value, but it must be in `application.yml`.
Expand All @@ -92,8 +100,6 @@ server:
port: 8080
```

#### How to run the web server
Applications will start listening the port immediately after running the `main` method;
for this, do not forget to add the `@ComponentScan(basePackages = "com.greenapi.server")` annotation.

Expand All @@ -109,7 +115,7 @@ public class WhatsappApiServerExample {
}
```

The handler function class must implement the `WebhookHandler` interface and be a bean.
The handler function class must implement the `WebhookHandler` interface and be a bean named `whatsappWebhookHandler`.
To do this, set the `@Component(value = "whatsappWebhookHandler")` annotation on the handler function class.

Link to example: [WebhookHandlerExample.java](src/main/java/com/greenapi/server/examples/WebhookHandlerExample.java).
Expand All @@ -128,10 +134,11 @@ public class WebhookHandlerExample implements WebhookHandler {
}
```

Webhook URL: `{{your host}}/green-api/async/webhook`
When a new notification is received, your `handle()` handler function will be executed asynchronously.
We recommend processing notifications asynchronously, since they are configured to timeout when receive status code 200 too long time.
After a timeout, the second attempt does not occur immediately, which can cause long processing of notifications and an increase in the message queue.
Webhook URL: `{{your host}}/whatsapp/async/webhook`
If you want your `handle()` handler function to be executed asynchronously.

Webhook URL: `{{your host}}/whatsapp/webhook`
If you want your `handle()` handler function to be called for each webhook sequentially in one thread.

Since each notification is automatically cast to a java object, you can filter the notification by any field yourself.
A description of the structure of notification objects can be found at this link: [Documentation](https://green-api.com/docs/api/receiving/notifications-format/type-webhook/)
Expand Down
4 changes: 2 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
</parent>
<groupId>com.green-api</groupId>
<artifactId>whatsapp-api-webhook-server-java</artifactId>
<version>0.1.2</version>
<version>0.1.3</version>
<name>whatsapp-api-webhook-server-java</name>
<description>whatsapp-api-webhook-server-java</description>
<licenses>
Expand All @@ -34,7 +34,7 @@
</developers>
<properties>
<java.version>17</java.version>
<whatsapp-api-client-java.version>0.1.2</whatsapp-api-client-java.version>
<whatsapp-api-client-java.version>0.1.3</whatsapp-api-client-java.version>
<snakeyaml.version>2.2</snakeyaml.version>
</properties>
<distributionManagement>
Expand Down
27 changes: 15 additions & 12 deletions src/main/java/com/greenapi/server/docs/README_RU.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,22 @@ sudo ufw enable

### Импорт

```xml
Установите библиотеку в проект своего сервера. Библиотека доступна в центральном репозитории Maven.

Maven
```xml
<dependency>
<groupId>com.green-api</groupId>
<artifactId>whatsapp-api-webhook-server-java</artifactId>
<version>{{version}}</version>
</dependency>
```

Gradle
```yaml
implementation group: 'com.green-api', name: 'whatsapp-api-client-java', version: 'version'
```
### Примеры
#### Как инициализировать объект
Expand All @@ -93,15 +100,12 @@ server:
port: 8080
```

#### Как запустить веб-сервер
Приложения начнет слушать порт, сразу после запуска метода `main`, для этого не забудьте поставить
аннотацию `@ComponentScan(basePackages = "com.greenapi.server")`.
аннотацию `@ComponentScan(basePackages = "com.greenapi.server")`, чтобы в вашем проекте были доступны все стандартные бины библиотеки.

Ссылка на пример: [WhatsappApiServerExample.java](/com/greenapi/server/examples/WhatsappApiServerExample.java).

```java
@SpringBootApplication
@ComponentScan(basePackages = "com.greenapi.server")
public class WhatsappApiServerExample {
Expand All @@ -111,13 +115,12 @@ public class WhatsappApiServerExample {
}
```

Класс функции-обработчика должен имплементировать интерфейс `WebhookHandler` и быть бином.
Класс функции-обработчика должен имплементировать интерфейс `WebhookHandler` и быть бином с именем `whatsappWebhookHandler`.
Для этого установите аннотацию `@Component(value = "whatsappWebhookHandler")` над классом функции-обработчика.

Ссылка на пример: [WebhookHandlerExample.java](/com/greenapi/server/examples/WebhookHandlerExample.java).

```java
@Component(value = "whatsappWebhookHandler")
public class WebhookHandlerExample implements WebhookHandler {
Expand All @@ -131,11 +134,11 @@ public class WebhookHandlerExample implements WebhookHandler {
}
```

Webhook URL: `{{your host}}/green-api/async/webhook`
При получении нового уведомления ваша функция-обработчик `handle()` будет выполнена асинхронно.
Мы рекомендуем обрабатывать уведомления асинхронно, так как они настроены на таймаут при долгом получении статус кода 200.
После таймаута вторая попытка происходит не сразу, что может послужить причиной долгой обработки уведомлений и
увеличения очереди сообщений.
Webhook URL: `{{your host}}/green-api/async/webhook`
Если вы хотите чтобы ваша функция-обработчик `handle()` будет выполнена асинхронно.

Webhook URL: `{{your host}}/green-api/webhook`
Если вы хотите чтобы ваша функция-обработчик `handle()` вызывалась для каждого вебхука последовательно в одном потоке.

Так как каждое уведомление автоматически кастится до java объекта, вы можете фильтровать уведомление по любому полю самостоятельно.
С описанием структуры объектов уведомлений можно ознакомиться по этой ссылке: [Документация](https://green-api.com/docs/api/receiving/notifications-format/type-webhook/)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@
import com.greenapi.client.pkg.api.webhook.WebhookHandler;
import com.greenapi.client.pkg.models.notifications.Notification;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;

@Component(value = "whatsappWebhookHandler")
//@Component(value = "whatsappWebhookHandler")
class WebhookHandlerExample implements WebhookHandler {
@SneakyThrows
@Override
public void handle(Notification notification) {
System.out.println("START " + notification);
Thread.sleep(20000);
Thread.sleep(10000);
System.out.println("END " + notification);
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package com.greenapi.server.examples;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
* Use "main" in method name instead "example" in real code.
*/
@SpringBootApplication
@ComponentScan(basePackages = "com.greenapi.server")
//@SpringBootApplication
//@ComponentScan(basePackages = "com.greenapi.server")
public class WhatsappApiServerExample {
public static void example(String[] args) {
SpringApplication.run(WhatsappApiServerExample.class, args);
Expand Down
16 changes: 15 additions & 1 deletion src/main/java/com/greenapi/server/pkg/WebhookServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/green-api")
@RequestMapping("/whatsapp")
@RequiredArgsConstructor
@Log4j2
public class WebhookServer {
Expand All @@ -35,4 +35,18 @@ public ResponseEntity<Void> receiveAsyncWebhook(@RequestBody String jsonString,
}
return ResponseEntity.status(HttpStatus.OK).build();
}

@PostMapping("/webhook")
public ResponseEntity<Void> receiveWebhook(@RequestBody String jsonString,
@RequestHeader(required = false) String Authorization) {
if ((Authorization != null && Authorization.replaceAll("Bearer ", "").equals(webhookToken)) ||
Objects.equals(webhookToken, "")) {

whatsappWebhookHandler.handle(notificationMapper.get(jsonString));

} else {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
}
return ResponseEntity.status(HttpStatus.OK).build();
}
}

0 comments on commit 1ddb967

Please sign in to comment.