Configurar la Event Function
Ahora configuremos la event function Cliq_Notifier, que envía automáticamente un mensaje a un canal de Zoho Cliq. Este mensaje incluirá los detalles de las facturas de los nuevos clientes que han completado exitosamente su pago. La función se ejecutará cuando sea activada por Catalyst Signals.
El directorio de funciones, functions/Cliq_Notifier contiene:
- El archivo principal de la función CliqNotifier.java
- El archivo de configuración catalyst-config.json
- Los archivos de biblioteca de Java en la carpeta lib
- Los archivos de dependencias .classpath y .project
Agregarás código en el archivo CliqNotifier.java.
Puedes copiar directamente el código a continuación y pegarlo en CliqNotifier.java ubicado en el directorio functions/Cliq_Notifier y guardar el archivo.
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Arrays;
import java.io.IOException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import com.catalyst.Context;
import com.catalyst.event.EVENT_STATUS;
import com.catalyst.event.EventRequest;
import com.catalyst.event.CatalystEventHandler;
import com.zc.auth.connectors.ZCConnection;
import okhttp3.OkHttpClient;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class CliqNotifier implements CatalystEventHandler {
private static final Logger LOGGER = Logger.getLogger(CliqNotifier.class.getName());
private static final String ZBOOKSDOMAIN = "{{YOUR_ZBOOKS_DOMAIN}}"; //Ingresa tu dominio de ZohoBooks según tu región
private static final String ZBOOKSORG = "{{YOUR_ZBOOKS_ORGANIZATION_ID}}"; //Ingresa tu ID de organización de ZohoBooks
private static final String ZCLIQDOMAIN = "{{YOUR_ZCLIQ_DOMAIN}}"; //Ingresa tu dominio de ZohoCliq según tu región
private static final String ZCLIQ_CHANNEL_UNIQUE_NAME = "{{YOUR_CHANNEL_UNIQUE_NAME}}"; //Ingresa el nombre único del canal donde se deben publicar las actualizaciones
private static final String ZCLIQ_BOT_UNIQUE_NAME = "{{YOUR_BOT_UNIQUE_NAME}}"; //Ingresa el nombre único del bot que publicará los mensajes
private static final String ZACCOUNTSDOMAIN = "{{YOUR_ZACCOUNTS_DOMAIN}}"; //Ingresa tu dominio de ZohoAccounts según tu región
@Override
public EVENT_STATUS handleEvent(EventRequest event, Context context) throws Exception {
try {
JSONArray data = extractInvoiceData(event);
JSONArray rows = transformInvoiceData(data);
JSONObject requestBody = prepareCliqRequest(rows);
String accessToken = getAccessToken();
sendToCliq(requestBody, accessToken);
LOGGER.log(Level.INFO, "Message pushed to channel successfully");
return EVENT_STATUS.SUCCESS;
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "An unexpected error occurred: ", e);
return EVENT_STATUS.FAILURE;
}
}
private JSONArray extractInvoiceData(EventRequest event) throws JSONException {
JSONObject payload = (JSONObject) event.getRawData();
JSONArray data = payload.getJSONArray("data");
JSONArray rows = new JSONArray();
for (int i = 0; i < data.length(); i++) {
JSONArray invoices = data.getJSONArray(i);
for (int j = 0; j < invoices.length(); j++) {
rows.put(invoices.getJSONObject(j));
}
}
return rows;
}
private JSONArray transformInvoiceData(JSONArray rows) throws JSONException {
for (int i = 0; i < rows.length(); i++) {
JSONObject row = rows.getJSONObject(i);
String invoiceId = row.optString("Invoice Id");
row.put("Link", "https://" + ZBOOKSDOMAIN + "/app/" + ZBOOKSORG + "#/invoices/" + invoiceId);
row.remove("Invoice Id");
}
return rows;
}
private JSONObject prepareCliqRequest(JSONArray rows) throws JSONException {
JSONArray headers = new JSONArray(Arrays.asList(
"Customer",
"Invoice Number",
"Amount",
"Paid On",
"Link"
));
JSONObject tableData = new JSONObject()
.put("headers", headers)
.put("rows", rows);
JSONObject slide = new JSONObject()
.put("type", "table")
.put("data", tableData);
return new JSONObject()
.put("text", "Here are the invoices marked as Paid in the last hour:")
.put("slides", new JSONArray().put(slide));
}
@SuppressWarnings("unchecked")
private String getAccessToken() throws Exception {
org.json.simple.JSONObject authConfig = new org.json.simple.JSONObject();
org.json.simple.JSONObject connectorConfig = new org.json.simple.JSONObject();
authConfig.put("client_id", "{{YOUR_CLIENT_ID}}"); //Ingresa tu Client ID
authConfig.put("client_secret", "{{YOUR_CLIENT_SECRET}}"); //Ingresa tu Client Secret
authConfig.put("auth_url", "https://" + ZACCOUNTSDOMAIN + "/oauth/v2/auth");
authConfig.put("refresh_url", "https://" + ZACCOUNTSDOMAIN + "/oauth/v2/token");
authConfig.put("refresh_token", "{{YOUR_REFRESH_TOKEN}}"); //Ingresa tu Refresh Token
connectorConfig.put("CliqConnector", authConfig);
return ZCConnection.getInstance(connectorConfig).getConnector("CliqConnector").getAccessToken();
}
private void sendToCliq(JSONObject payload, String accessToken) throws IOException {
String cliqUrl = "https://" + ZCLIQDOMAIN + "/api/v2/channelsbyname/" + ZCLIQ_CHANNEL_UNIQUE_NAME + "/message?bot_unique_name=" + ZCLIQ_BOT_UNIQUE_NAME;
Request request = new Request.Builder()
.url(cliqUrl)
.addHeader("Authorization", "Zoho-oauthtoken " + accessToken)
.addHeader("Content-Type", "application/json")
.post(RequestBody.create(MediaType.parse("application/json"), payload.toString()))
.build();
try (Response response = new OkHttpClient().newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected response from Cliq API: " + response.body().string());
}
}
}
}
-
Dominio de Zoho Books (línea 27): Ingresa el dominio correspondiente a tu organización de Zoho Books, según tu región. Ejemplo: books.zoho.com, books.zoho.eu o books.zoho.in
-
ID de organización de Zoho Books (línea 28): Proporciona el ID de organización único de tu cuenta de Zoho Books.
-
Dominio de Zoho Cliq (línea 30): Especifica el dominio de tu organización de Zoho Cliq, según tu región. Ejemplo: cliq.zoho.com, cliq.zoho.eu
-
Nombre único de tu canal de Zoho Cliq (línea 31): Ingresa el nombre único del canal de Zoho Cliq donde se deben publicar las actualizaciones de facturas pagadas.
-
Nombre único de tu bot de Zoho Cliq (línea 32): Proporciona el nombre único del bot de Zoho Cliq que se ha agregado al canal anterior.
-
Dominio de Zoho Accounts (línea 34): Indica el dominio de Zoho Accounts utilizado para iniciar sesión en Catalyst, Zoho Books y Zoho Cliq. Ejemplo: accounts.zoho.com, accounts.zoho.in
-
Client ID (línea 109): Pega el Client ID obtenido durante el registro del cliente en el Paso 4.
-
Client Secret (línea 110): Pega el Client Secret correspondiente generado en el Paso 4.
-
Refresh Token (línea 113): Proporciona el Refresh Token que generaste en el Paso 5 usando tu herramienta de cliente de API.
La Event Function ahora está configurada.
Última actualización 2026-03-20 21:51:56 +0530 IST