Notifiche

Come seguire questo capitolo

Dati richiesti: Credenziali SUPERADMIN esistenti e URL di callback sotto il tuo controllo.

Passaggi e risultato atteso: Crea o identifica il destinatario amministrativo, quindi invia la selezione completa delle notifiche. adminUserId identifica qui il destinatario, separatamente dal userId del percorso cliente.

Alternative e operazioni successive: Integrazione amministrativa opzionale. Subscribe sostituisce la selezione; includi tutti gli eventi che vuoi mantenere.

Codice sorgente dei DTO: AdminOutputModel, SystemOccurrenceOutputModel, SystemOccurrencePreferenceInputModel

Le variabili assegnate in un blocco precedente vengono riutilizzate nei successivi. I dati inseriti dal cliente provengono dalla tua interfaccia. Conserva identificativi e valori di riferimento nel contesto del cliente; non ricreare il contesto a ogni passaggio.

Gli esempi utilizzano classi helper condivise. Consulta Classi helper condivise: codice C# e Java completo prima di copiare un esempio.
Prima di iniziare: Client HTTP configurato e credenziali SUPERADMIN esistenti per creare il destinatario. Imposta callbackUrl con l’indirizzo controllato; nome, cognome, e-mail e telefono identificano il destinatario amministrativo.
Da conservare per il passaggio successivo: Preferenze di notifica di adminUserId. La creazione di un amministratore non restituisce un token di accesso amministrativo.
Il microservizio di notifiche WMS2 può segnalare eventi come apertura, modifica del portafoglio o modifica dei dati del cliente.
Le notifiche possono essere inviate tramite:
  • E-mail
  • SMS
  • Callback HTTP
Sono destinate agli utenti SELLER, ADMIN o SUPERADMIN.

Iscrizione

Un SUPERADMIN esistente crea qui un destinatario ADMIN e configura la notifica PORTFOLIO-ORDER-SUBMISSION-DELIVERED. Entrambe le richieste usano il token SUPERADMIN esistente; la creazione non fornisce un nuovo token al destinatario.
L’esempio usa un callback HTTP, detto anche webhook, per un evento di sistema.
L’indirizzo del webhook è definito per utente, come e-mail e numero mobile. Ogni utente ha il proprio URL di callback HTTP.
L’elenco completo dei codici evento è disponibile in api/v1/system-occurrence.
Per un test isolato con dati fittizi, usa webhook.site. Il sito mostra un URL univoco da utilizzare per il callback:
Dove trovare l’URL di callback per il test
Crea quindi un utente ADMIN e imposta la proprietà URL con l’indirizzo HTTP generato da webhook.site. Per creare l’utente ADMIN è richiesto un token SUPERADMIN:
								
var createAdminPayload = new
{
    Name = name,
    Surname = surname,
    Email = email,
    PhoneNumberPrefix = phoneNumberPrefix,
    PhoneNumberNumber = phoneNumberNumber,
    Url = callbackUrl,
    GenderId = genderId,
    LanguageId = languageId
};
// Creating an ADMIN user requires an existing SUPERADMIN token.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", superAdminToken);
using var response = await httpClient.PostAsync("api/v1/users/admins",
    new StringContent(JsonConvert.SerializeObject(createAdminPayload), Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();
var admin = JsonConvert.DeserializeObject<AdminOutputModel>(await response.Content.ReadAsStringAsync());
var adminUserId = admin.Id;

									
								
JsonObject payload = new JsonObject();
payload.addProperty("Name", name);
payload.addProperty("Surname", surname);
payload.addProperty("Email", email);
payload.addProperty("PhoneNumberPrefix", phoneNumberPrefix);
payload.addProperty("PhoneNumberNumber", phoneNumberNumber);
payload.addProperty("Url", callbackUrl);
payload.addProperty("GenderId", genderId);
payload.addProperty("LanguageId", languageId);
HttpRequest request = HttpRequest.newBuilder()
    .uri(Settings.wmsUri("users/admins"))
    .timeout(Duration.ofMinutes(1))
    .header("Authorization", "Bearer " + Settings.SUPERADMIN_TOKEN)
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(payload.toString())).build();
var response = httpClient.send(request, BodyHandlers.ofString());
Api.requireSuccess(response);
AdminOutputModel admin = new Gson().fromJson(response.body(), AdminOutputModel.class);
var adminUserId = admin.Id;

Configura quindi le preferenze per adminUserId. Il chiamante deve essere autorizzato a gestire il destinatario. Qui scegliamo la notifica tramite callback HTTP:
								
// Use a token authorized to manage adminUserId, such as superAdminToken.
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", superAdminToken);
var systemOccurrences = await httpClient.GetFromJsonAsync<List<SystemOccurrenceOutputModel>>("api/v1/system-occurrence");

  // Get PORTFOLIO-ORDER-SUBMISSION-DELIVERED system notification ID
  var systemOccurrenceId = systemOccurrences.First(x => x.Code == "PORTFOLIO-ORDER-SUBMISSION-DELIVERED").Id;

  var selectedSystemNotifications = new List<SystemOccurrencePreferenceInputModel>();
  selectedSystemNotifications.Add(new SystemOccurrencePreferenceInputModel
  {
	Id = systemOccurrenceId,
	IsEmailEnabled = false,
	IsHttpEnabled = true,	// HTTP callback
	IsSmsEnabled = false
  });

  var payLoadAsString = JsonConvert.SerializeObject(selectedSystemNotifications);
  using var response = await httpClient.PostAsync($"api/v1/system-occurrence/user/{adminUserId}",
    new StringContent(payLoadAsString, Encoding.UTF8, "application/json"));
response.EnsureSuccessStatusCode();

									
								
HttpRequest eventsRequest = HttpRequest.newBuilder()
    .uri(Settings.wmsUri("system-occurrence"))
    .timeout(Duration.ofMinutes(1))
    .header("Authorization", "Bearer " + Settings.SUPERADMIN_TOKEN).GET().build();
var eventsResponse = httpClient.send(eventsRequest, BodyHandlers.ofString());
Api.requireSuccess(eventsResponse);
Type eventListType = new TypeToken<List<SystemOccurrenceOutputModel>>() {}.getType();
List<SystemOccurrenceOutputModel> events = new Gson().fromJson(eventsResponse.body(), eventListType);
var event = events.stream()
    .filter(x -> "PORTFOLIO-ORDER-SUBMISSION-DELIVERED".equals(x.Code))
    .findFirst().orElseThrow(() -> new IllegalStateException("Event unavailable in this environment"));
JsonObject preference = new JsonObject();
preference.addProperty("Id", event.Id);
preference.addProperty("IsEmailEnabled", false);
preference.addProperty("IsSmsEnabled", false);
preference.addProperty("IsHttpEnabled", true);
JsonArray preferences = new JsonArray();
preferences.add(preference);
HttpRequest subscriptionRequest = HttpRequest.newBuilder()
    .uri(Settings.wmsUri("system-occurrence/user/" + adminUserId))
    .timeout(Duration.ofMinutes(1))
    .header("Authorization", "Bearer " + Settings.SUPERADMIN_TOKEN)
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(preferences.toString())).build();
var subscriptionResponse = httpClient.send(subscriptionRequest, BodyHandlers.ofString());
Api.requireSuccess(subscriptionResponse);

Le preferenze sostituiscono l’intera selezione esistente; gli eventi omessi sono disattivati. Leggi e includi le preferenze da mantenere. Un elenco vuoto disattiva tutte le notifiche. Questo esempio si iscrive alla consegna riuscita dell’ordine. La consegna alla banca depositaria avviene dopo l’accettazione della richiesta da parte dell’API. Eventi e canali dipendono dal servizio installato e dall’ambiente.
Per verificare, crea un cliente con la procedura Registrazione del cliente e invia un ordine di apertura. L’immagine mostra un callback ricevuto dopo l’evento sottoscritto:
Esempio di notifica ricevuta tramite callback