Menu delle guide

Identificare gli utenti

Per impostazione predefinita, ogni visitatore è un ospite. Quando un utente accede al tuo sito o alla tua app, il server può firmare per lui un breve token di identità, così Kavchat sa chi è.

Perché identificare gli utenti

  • Il tuo ID utente in ogni ticket. Le conversazioni e i ticket riportano l'ID utente del tuo sistema (userId nel ticket), così il team sa a quale account appartengono.
  • Nessun recapito da inserire. Gli ospiti devono lasciare un'email o un numero di telefono nel modulo di contatto. Gli utenti identificati non sono obbligati a farlo.
  • Utenti di test. Quando il pubblico selezionato è "Utenti di test", il bot viene mostrato solo agli utenti il cui numero di telefono è nell'elenco degli utenti di test. Kavchat li riconosce dal numero di telefono nel token.
  • Un saluto personalizzato. {name} in un passaggio dello script viene sostituito con il nome dell'utente.

Il token

Il token di identità è un normale JWT creato sul tuo server:

  • Algoritmo HS256. La chiave è la tua chiave segreta: l'intera stringa sk_live_..., in byte UTF-8.
  • La pagina o l'app lo invia nell'header Authorization: Bearer <token> a ogni chiamata a Kavchat.
  • Non firmare mai i token nel browser o nell'app. La chiave segreta resta sul tuo server.
CampoObbligatorioDescrizione
subSìL'ID utente nel tuo sistema, da 1 a 128 caratteri.
expSìLa scadenza, al massimo tra 30 giorni. Negli SDK il valore predefinito è di 7 giorni.
phoneNoIn formato E.164 (+972501234567) o come numero locale. Serve a riconoscere gli utenti di test.
nameNoMostrato nel saluto e precompilato nel modulo di contatto.
emailNoPrecompilata nel modulo di contatto.

Crea un nuovo token quando l'utente accede e poi prima che quello precedente scada. Una durata breve, di pochi giorni, è una buona impostazione predefinita.

Installare un SDK per il server

Gli SDK per il server creano il token per te, verificano i webhook e chiamano la Server API. Non hanno dipendenze oltre alla libreria standard di ciascun linguaggio (Java ha una dipendenza da Jackson).

Node.js
yarn add @kavchat/node
# or: npm install @kavchat/node
Python
pip install kavchat
PHP
composer require kavchat/kavchat-php
Java
<!-- Maven, served by JitPack. Gradle: maven("https://jitpack.io") and implementation("com.kavchat:kavchat-java:0.0.11") -->
<repositories>
  <repository>
    <id>jitpack.io</id>
    <url>https://jitpack.io</url>
  </repository>
</repositories>

<dependency>
  <groupId>com.kavchat</groupId>
  <artifactId>kavchat-java</artifactId>
  <version>0.0.11</version>
</dependency>
.NET
dotnet add package Kavchat
Go
go get kavchat.com/kavchat-go
Ruby
# Gemfile
gem "kavchat"

Creare un token

Node.js
import { Kavchat } from '@kavchat/node';

const kavchat = new Kavchat(process.env.KAVCHAT_SECRET_KEY!);

const token = kavchat.createUserToken({
  userId: 'user_123',          // required, 1 to 128 characters
  phone: '+972501234567',      // optional
  name: 'Dana',                // optional
  email: 'dana@example.com',   // optional
  expiresIn: 7 * 24 * 3600,    // seconds, default 7 days, at most 30 days
});
// Send the token to your page or app and pass it to the Kavchat widget or SDK.
Python
import os
from kavchat import Kavchat

kavchat = Kavchat(os.environ["KAVCHAT_SECRET_KEY"])

token = kavchat.create_user_token(
    "user_123",                 # required, 1 to 128 characters
    phone="+972501234567",
    name="Dana",
    email="dana@example.com",
    expires_in=7 * 24 * 3600,   # seconds, default 7 days, at most 30 days
)
PHP
use Kavchat\Kavchat;

$kavchat = new Kavchat(getenv('KAVCHAT_SECRET_KEY'));

$token = $kavchat->createUserToken(
    'user_123',              // required, 1 to 128 characters
    phone: '+972501234567',
    name: 'Dana',
    email: 'dana@example.com',
    expiresIn: 7 * 24 * 3600 // seconds, default 7 days, at most 30 days
);
Java
KavchatClient kavchat = KavchatClient.builder(System.getenv("KAVCHAT_SECRET_KEY")).build();

String token = kavchat.createUserToken(UserTokenOptions.builder("user_123")
        .phone("+972501234567")
        .name("Dana")
        .email("dana@example.com")
        .expiresIn(Duration.ofDays(7))   // default 7 days, at most 30 days
        .build());
.NET
using Kavchat;

using var kavchat = new KavchatClient(Environment.GetEnvironmentVariable("KAVCHAT_SECRET_KEY")!);

var token = kavchat.CreateUserToken(new UserTokenOptions
{
    UserId = "user_123",                 // required, 1 to 128 characters
    Phone = "+972501234567",
    Name = "Dana",
    Email = "dana@example.com",
    ExpiresIn = TimeSpan.FromDays(7),    // default 7 days, at most 30 days
});
Go
import kavchat "kavchat.com/kavchat-go"

client := kavchat.New(os.Getenv("KAVCHAT_SECRET_KEY"))

token, err := client.CreateUserToken(kavchat.UserToken{
	UserID:    "user_123", // required, 1 to 128 characters
	Phone:     "+972501234567",
	Name:      "Dana",
	Email:     "dana@example.com",
	ExpiresIn: 7 * 24 * time.Hour, // zero means 7 days; at most 30 days
})
Ruby
require "kavchat"

kavchat = Kavchat::Client.new(ENV.fetch("KAVCHAT_SECRET_KEY"))

token = kavchat.create_user_token(
  user_id: "user_123",        # required, 1 to 128 characters
  phone: "+972501234567",
  name: "Dana",
  email: "dana@example.com",
  expires_in: 7 * 24 * 3600   # seconds, default 7 days, at most 30 days
)

Ogni SDK offre anche una versione autonoma che accetta la chiave segreta come primo argomento, ad esempio createUserToken(secretKey, options) in Node.js. Un ID utente vuoto o troppo lungo, oppure una durata non compresa tra un secondo e 30 giorni, genera un errore di argomento.

Senza SDK

Va bene qualsiasi libreria JWT. Questi sono gli stessi esempi mostrati nella pagina Installazione del pannello di controllo:

Node.js
import jwt from 'jsonwebtoken';

// On your server only. Never send the secret key to the browser.
const token = jwt.sign(
  { sub: user.id, phone: user.phone, name: user.firstName, email: user.email },
  process.env.KAVCHAT_SECRET_KEY, // sk_live_...
  { algorithm: 'HS256', expiresIn: '7d' },
);
Python
import jwt, time, os

token = jwt.encode(
    {"sub": user.id, "phone": user.phone, "name": user.first_name,
     "exp": int(time.time()) + 7 * 24 * 3600},
    os.environ["KAVCHAT_SECRET_KEY"],  # sk_live_...
    algorithm="HS256",
)
PHP
use Firebase\JWT\JWT;

$token = JWT::encode([
    'sub'   => $user->id,
    'phone' => $user->phone,
    'name'  => $user->first_name,
    'exp'   => time() + 7 * 24 * 3600,
], getenv('KAVCHAT_SECRET_KEY'), 'HS256'); // sk_live_...

Passare il token alla chat

Invia il token alla pagina o all'app, ad esempio insieme alla risposta alla chiamata di accesso, e passalo al widget o all'SDK. Cambiare utente ricarica il bot e avvia una nuova conversazione.

Website
// at page load, with a token your server created for the signed-in user
Kavchat.init({ publicKey: 'pk_live_...', userToken: token, userName: 'Dana' });
// later, after login or logout
Kavchat.setUser({ token, name: 'Dana' });
Kavchat.setUser(null);
React Native
<KavchatProvider publicKey="pk_live_..." userToken={session?.kavchatToken} userName={session?.firstName}>
Flutter
await kavchat.setUser(token: jwt, name: 'Dana'); // after login
await kavchat.setUser(token: null);              // after logout
iOS
Kavchat.setUser(token: identityToken, name: "Dana")    // after login
Kavchat.setUser(token: nil)                            // after logout
Android
Kavchat.setUser(token = identityToken, name = "Dana")   // after login
Kavchat.setUser(token = null)                           // after logout

Trovi maggiori dettagli in ogni guida: sito web, React Native, Flutter, iOS, Android.

Quando il token viene rifiutato

Un token scaduto, firmato con un'altra chiave o privo di sub viene rifiutato con HTTP 401 e il codice di errore identity_invalid. Controlla l'orologio del server, la chiave e che exp non sia oltre 30 giorni nel futuro.