Come funzionano i webhook in HireHop

HireHop può inviare un messaggio con dati ad altre app quando determinati eventi vengono attivati all’interno di HireHop. Questo messaggio è chiamato webhook che invia automaticamente i dati rilevanti nella posizione richiesta.

WebhooksCos’è un webhook?

Un webhook invia/spinge un messaggio, con i dati allegati al messaggio, quando accadono cose specifiche in HireHop (un evento). I webhook vengono inviati tramite HTTP (chiama un indirizzo web) e sono un modo per inviare dati ad altre applicazioni in tempo reale. I webhook forniscono i dati rilevanti ad applicazioni specifiche non appena si verificano, il che significa che l’applicazione ricevente ottiene i dati immediatamente dopo che si verifica l’evento, il che è molto più efficiente e veloce del polling per le modifiche ai dati..

I webhook HireHop possono essere utilizzati per comunicare direttamente con altre app o essere inviati a un connettore come Zapier, che può essere creato per formattare i dati ed effettuare le chiamate API necessarie a HireHop o a un’altra applicazione.

Configurazione di un webhook

In HireHop, vai su “Impostazioni”, quindi fai clic sulla scheda “Impostazioni azienda” e sul pulsante “Webhook” nella parte superiore della pagina. Nella finestra popup, fai clic sul pulsante “Nuovo” e aggiungi l’URL a cui deve essere inviato il messaggio webhook e seleziona ogni webhook a cui desideri che l’URL risponda. Puoi aggiungere tutti i webhook che desideri, ma dovresti limitarli solo a quelli necessari a cui risponderà l’URL specifico.

Un webhook HireHop pubblicherà i dati sull’endpoint URL come JSON e conterrà i dati seguenti o simili.

{
    "time": "2022-03-29 07:50:42",
    "user_id": 1,
    "user_name": "John Smith",
    "user_email": "john@email.com",
    "company_id": 1,
    "export_key": "22u43mrjwe7u",
    "event": "invoice.status.updated",
    "data": { ... },
    "changes": {
        "FIELD_NAME": {
            "from": "vecchio",
            "to": "nuovo"
        }, ...
    }
}

Nell’esempio JSON sopra, i seguenti campi sono:

  • time” è l’ora UTC e la data in cui è stato inviato il webhook.
  • user_id” è l’ID dell’utente che ha causato l’attivazione dell’evento.
  • user_name” è il nome dell’utente.
  • company_id” è l’identificatore numerico univoco dell’azienda per cui l’utente lavora.
  • export_key” è il valore della chiave di esportazione nelle impostazioni dell’azienda che può essere utilizzata come controllo di sicurezza.
  • event” è il nome dell’evento webhook che è stato attivato.
  • data” sono i dati che appartengono all’evento webhook.
  • changes” sono i campi che sono cambiati, essendo ciò che erano rispetto a ciò in cui sono stati modificati.

HireHop non attende una risposta dall’URL chiamato né segnala un errore HTTP durante la sua chiamata.

Il codice PHP di esempio per un endpoint URL per acquisire i dati del webhook sarebbe:

<?php
	// Ottieni i dati JSON
	$postdata = file_get_contents('php://input');
	// Converti i dati JSON in un oggetto
	$data_str = json_decode($postdata);
?>

 

Posted in API

HireHop Rest API – Guida introduttiva

HireHop è basato su un’API, il che significa che tutto ciò che vedi fare da HireHop, puoi anche farlo utilizzando l’API estesa. Tutto ciò di cui hai bisogno per accedere all’API Rest è un token utente applicato come GET o POST all’endpoint URL pertinente.

Token API

Per generare un token API, vai alla pagina “Impostazioni” e seleziona la scheda “Utenti”. Seleziona o crea un utente, quindi mentre è selezionato quell’utente specifico, fai clic sul pulsante “Menu”, quindi sull’opzione “Token API” per generare un token. Il token verrà quindi visualizzato e potrà essere copiato negli appunti utilizzando il pulsante di copia.

Il token non sarà più valido se si modifica l’e-mail o la password dell’utente selezionato o se si accede successivamente a quell’utente. Per evitare che ciò accada, dovresti creare un utente API dedicato e, per sicurezza, fornirgli le autorizzazioni pertinenti, limitandolo così da tutto ciò per cui non utilizzerai l’API.

Per motivi di sicurezza, non dovresti usare il token nel codice JavaScript front-end, dovrebbe essere usato solo lato server, come se un hacker ottiene il token, può modificare e accedere ai tuoi dati su HireHop, quindi mantieni il tuo token segreto. Se il tuo token viene trapelato, cambia semplicemente la password dell’utente API e genera un nuovo token.

Utilizzo di un Token

Un token deve essere impostato come parametro GET o POST denominato “token”. Ad esempio, per caricare i dati del lavoro per il lavoro numero 52, HireHop chiamerà l’endpoint API:

https://myhirehop.com/php_functions/job_refresh.php?job=52

Se vuoi chiamare lo stesso endpoint usando un token, l’URL sarebbe:

https://myhirehop.com/php_functions/job_refresh.php?job=52&token=dqwejk5GVT65909bHHBN7922pq5hxjm%207hmn

Ricorda che quando passi il token tramite GET (un parametro URL come sopra), devi prima codificare il token utilizzando uno strumento come https://meyerweb.com/eric/tools/dencoder.

Dati di Pubblicazione

Per creare o modificare i dati in HireHop è necessario utilizzare un POST. Quando si inviano i dati, è necessario impostare solo i campi che si desidera modificare, ad esempio per creare o modificare un lavoro utilizzando l’endpoint https://myhirehop.com/php_functions/job_save.php, impostando il parametro “job” su “0 ” o omettendolo creerà un nuovo lavoro, qualsiasi altra cosa modificherà il numero di lavoro pertinente. Quindi, per modificare il nome dell’azienda nel lavoro numero 52, i dati del post dovrebbero essere:

{
"job" : 52,
"name" : "New Name",
"token" : "dqwejk5GVT65909bHHBN7922pq5hxjm=-7hmn"
}

Endpoint API

Molti endpoint API sono documentati nella documentazione API, con molti altri da seguire.  Per stabilire l’endpoint per un’attività, nell’applicazione HireHop, utilizzare la console del browser per controllare le chiamate di rete e quali parametri sono impostati. A breve sarà pubblicata una guida completa agli endpoint URL.

Limiti tariffari

HireHop consente a ciascun utente 60 richieste di connessione in un periodo di 1 minuto. Se sono presenti più di 60, viene restituito un errore “Avviso di sicurezza, troppe transazioni” (327).

Posted in API

Cross Domain Fonts CORS – CSS font-face not loading

Many users have created some amazing documents for use in HireHop, utilizing HTML5, JavaScript and CSS functionality.  For these documents users sometimes need a special font that they store on their server, however, sometimes the font doesn’t seem to work in the HireHop document.  The reason for this is because of Cross-Origin Resource Sharing (CORS) restrictions in browsers.

Fonts Not Loading in Documents & Web Pages

Most web browsers do not allow cross-domain requests, this is because of the same origin security policy. The result is that sometimes when using web-fonts from another domain, this can cause errors and the font does not load in the web page (or HireHop documents). Basically, for security reasons, some files are being “flagged” as not being allowed to be used across different domains by the server that hosts them, so the following typical code might not seem to work:

<style type="text/css">
@font-face {
    font-family: "OpenSans";
    src: url("https://my_server.com/fonts/OpenSans.woff2") format("woff2");
}
html, body{
    font: normal 16px OpenSans, sans-serif;
}
</style>

The Solution

To fix cross-origin restrictions for your fonts, the response from remote server that hosts the font files must include the Access-Control-Allow-Origin header in the font file.

If you’re using font services like Typekit or Google Fonts, or maybe content delivery networks like BootstrapCDN, CdnJS or JsDelivr to load your prefered fonts, you don’t need to do anything, because the Access-Control-Allow-Origin header is already sent in their response header.

Apache

To configure an Apache web server, put the following code into the httpd.conf or .htaccess file.

  1. Add the mime type headers on Apache:
    AddType application/vnd.ms-fontobject    .eot
    AddType application/x-font-opentype      .otf
    AddType image/svg+xml                    .svg
    AddType application/x-font-ttf           .ttf
    AddType application/font-woff            .woff
    AddType application/font-woff2           .woff2
    
  2. Enable cross-origin resource sharing (CORS) on Apache for the mime types:
    <IfModule mod_headers.c>
      <FilesMatch ".(eot|otf|svg|ttf|woff|woff2?)$">
        Header set Access-Control-Allow-Origin "*"
      </FilesMatch>
    </IfModule>
    

NGINX

To configure an NGINX web server, put the following code into the /etc/nginx/nginx.conf or your custom /etc/nginx/conf.d/custom.conf file.

  1. Add the mime type headers on NGINX:
    application/vnd.ms-fontobject    eot;
    application/x-font-opentype      otf;
    image/svg+xml                    svg;
    application/x-font-ttf           ttf;
    application/font-woff            woff;
    application/font-woff2           woff2;
    
  2. Enable cross-origin resource sharing (CORS) on NGINX for the mime types:
    location ~* .(eot|otf|svg|ttf|woff|woff2)$ {
        add_header Access-Control-Allow-Origin *;
    }
    

IIS

To configure the Microsoft IIS, add the following the code to the web.config system.webServer block.

  • Enable cross-origin resource sharing (CORS) on IIS
    <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="access-control-allow-origin" value="*" />
          <add name="access-control-allow-headers" value="content-type" />
        </customHeaders>
      </httpProtocol>
    </system.webServer>
    

PHP

If you can’t change the server settings, you can always use PHP to deliver the font file.

  • Use a server script file rather than a physical font file
    <style type="text/css">
    @font-face {
        font-family: 'OpenSans';
        src: url('https://my_server.com/fonts/OpenSans.php') format('woff2');
    }
    html, body{
        font: normal 16px OpenSans, sans-serif;
    }
    </style>
    
  • How to fix cross-domain @font-face issues with PHP
    <?php
    // fonts.php
    header('Access-Control-Allow-Origin: *');
    header('Content-Type: application/font-woff2');
    echo @file_get_contents('/fonts/OpenSans.woff2');
    ?>
    
Posted in API

Customisation & Customising Widgets – HireHop API NoHTML Framework

HireHop is completely customisable, you can even add custom fields, all done using the HireHop JavaScript injection method, in which JavaScript files that you have written are inserted into HireHop pages.  If you look at the page source of a HireHop page, you will see <!– PLUGINS –>, it is after here where the JavaScript for your plugins will be inserted.

HireHop has been built from the ground up, developing our own framework that we call NoHTML, amalgamating existing technology and methodology to produce a framework that is easy to use, extendable and enables fast page loading, even on slow internet connections.

Apart from the main part of the page, the main parts of HireHop are dynamically built on the client machine using JavaScript and jQuery widgets, similar to REACT and JSX, but more simple and of course using the familiar jQuery framework.  For instance, if you load a Job page and inspect the page (press F12 for the browser’s object inspector), you will see a <div> element at the bottom of the page structured like so:

<div id=”notes_tab“></div>

As you can see the above <div> is just an empty div element. If you click on the “Notes” tab, suddenly the above element is populated with elements.  Looking at your browser’s inspector you will also notice that the only data loaded from the server was some JSON and not the code in the notes tab.  The notes tab was built dynamically on the client machine using a custom jQuery UI Widget called $.notes() (internally called $.custom.notes) that is defined in the file /js/notes.js, and that widget used an ajax call to the server to get the data to populate it.

All the widget files on HireHop are compressed for speed, however to see the expanded source just add a .MAX to the end of the file’s name, for instance /js/notes.MAX.js.

To inject JavaScript into your webpages, if you go to Settings->Company Settings, and in Plugins add the url of your JavaScript file, which should be on an https server.  You can add multiple URLs which you can separate with a “;” (semi-colon).  All URLs must be to a secure https domain.

Extending A Widget

As these are jQuery UI Widgets, you can use a type of Object Orientated programming technique to overwrite parts of the HireHop widgets. For example, we are going to create a small plugin that adds a span element with the word Hello after the Refresh button on the notes widget.

First create a JavaScript file on your web server and add the following code

$(document).ready(function(){
// Check if the notes widget exists
if(typeof($.custom.notes)!=”undefined” && hh_api_version<=1) {
// Redefine notes widget
$.widget(“custom.notes“, $.custom.notes, {
_init_main: function() {
// Call the old _init_main
this._super(arguments);
// Add an hello after the refresh button
$(“<span>“,{ html:” Hello” }).insertAfter(this.btnRefresh);
},
// Even add your own new functions into the widget if you want

new_function_name: function() { }
});
}
});

The above code is available in a file located at https://s.myhirehop.com/plugins/demo.js.

Explaining the code above line by line:

$(document).ready(function(){
First we wait for the document to be ready and all page elements and JavaScript files to be loaded.  In this case this is not necessary as the /js/notes.js file is loaded before the plugin script, however for this example we have left it in for reference.

if(typeof($.custom.notes)!=”undefined” && hh_api_version<=1) {
Next we test to see if the notes widget has been defined, if it has we will proceed to overwrite one part of it.  Here we are also testing the HireHop API version the user is using.  As new versions of HireHop are released, the user will have the option to use it and this makes sure that your plugin is compatible with that version.

$.widget(“custom.notes“, $.custom.notes, {
Here we are initiating merging of a new JavaScript object containing functions into the notes widget.

_init_main: function() {
By naming a function the same as an existing one, it will be overwritten.

this._super(arguments);
This calls the inherited function, being the function we are overwriting.

$(“<span>”,{ html:” Hello” }).insertAfter(this.btnRefresh);
We then add a simple span element containing the word “Hello” after the Refresh button. you could also use $(“<span> Hello</span>”).insertAfter(this.btnRefresh);. To address elements, you should always use the variables assigned to elements and never the element ID’s as most ID’s on HireHop are dynamically created and will be different with every instance.  If the element ID has numbers in it or is not nicely named, definitely don’t use it.

new_function_name: function() { }
Finally, this does nothing and is not necessary for what we need to do, it just demonstrates that you can even add your own functions into the widget.

When you reload the HireHop page, you will see the word Hello after the refresh button if you did everything correctly.

Versioning

A huge advantage of using the HireHop NoHTML framework is that all the JavaScript is cached, resulting in fast page loading as the browser uses the JavaScript files in its cache.  This can be problematic when you update your plugin, as all the users using it, their browsers won’t download the updated version, and instead use their cached version, that is unless they clear their browser cache.

To overcome this, when adding your JavaScript URLs to the Plugins options, you can use a versioning parameter, for example for https://www.mywebsite.com/plugin.js you would enter it as https://www.mywebsite.com/plugin.js?v=1. After an update you can then change it to read https://www.mywebsite.com/plugin.js?v=2 which will force all browsers to reload the JavaScript file from your server.  If you don’t have a server to store the code on, you can always use GIST or Google Open Source.

Posted in API

Custom Fields – HireHop API

You can have an unlimited number of custom fields in HireHop specific to each record, a record being a job, project, test/service, asset, etc.  All custom fields can be used in documents, as long as they exist, otherwise they will just be blank.

Currently custom fields are only fully supported in Jobs and Projects. Custom fields can only be used using plugins.

Custom Fields Structure

When fetching a custom field for the currently edited record, there is a function called _get_custom_field_value(field) which will return NULL if the field is not set, a string, or a JavaScript object, depending on how you saved it.

You probably should save custom fields as a JavaScript object (like JSON) in the following format for more printing control, as if it is just a string, HireHop will treat it as a string:

"field_name" :
{
"value"  : "The value of the field",
"type"   : "The field type, default is text, it can also be number, currency, text, date, html and array"
"format" : "For date type only, eg "ddd, dddddd tt" // = "Mon, January 1 2017 12:00"
}

  • value is the value of the field in any format.
  • type tells HireHop how the field should be treated when merging it into a document. An array field will be displayed as JSON.
  • format tells HireHop how to format the field in the document, currently only available dates and is dependent on the users settings and how their date and time formats are set:
    • dddddd for a long date (like January 1 2018)
    • ddddd for a short date (like 01/01/2018)
    • dddd for the day of the week (like Monday)
    • ddd for the short day of the week (like Mon)
    • tt for the time (like 12:36 am).

The format part is only needed for dates and if it is not set, nothing will show.  You can merge formats together and add separators, for instance you can use dddd, dddddd tt which will give “Monday, January 1 2018 12:00” if the user has set a date order as day month year. The value for a date type must be stored in the yyyy-mm-dd hh:mm format.

If you just save the field as a string and not a JavaScript object, that’s fine, HireHop will just treat it as a string.  Saving your custom fields as a JavaScript object will give you greater control, especially when HireHop prints them in a document.

Saving The Custom Fields

On all edit forms that support custom fields, there is a function called _save_custom_field_value(field, value).  This stores your fields to be saved later.  If you can’t find the function, please contact us.

Please note, that all changes must be written prior to saving.

When the custom fields are saved, they are merged with the existing fields, and any new fields passed with the same name as any existing ones, the new values will be set.

When saving the custom fields, for example using /php_functions.job_save.php directly as an API call, only parameters set will be updated, so if you only set the custom_fields post parameter, only the custom fields will change, all the other fields will stay as is.

Printing Custom Fields

All custom fields can be incorporated into documents just like normal fields and are prefixed with a single “_” (underscore) character.  For example, for a custom field in a job called “field_name”, you would load it by using the merge field “job:_field_name“.

Naming Custom Fields

Some custom fields in documents merge fields together, for example tests merge with an asset in some document fields, so be careful not to use the same field name in an asset and a test.  Also, other plugins maybe added in the future written by yourself or from another source, so add a prefix that denominates you, for example plugins written HireHop by use the “hh_” prefix, so a field written in a plugin by us might be called “hh_NewName”.  Field names in document merges are not case sensitive, but they obviously are in JavaScript.

Searchable Custom Field

There is an additional field called CUSTOM_INDEX, that can be used for searching, filtering and listed in search results.  The field is a 45 character string value that can be set to NULL. To enable the field to be shown in the search results on the home page, change the allSearchCols global JavaScript variable by adding CUSTOM_INDEX to it:

if(allSearchCols.constructor===Array && doc_type==0 ) {
allSearchCols.push("CUSTOM_INDEX");
}

There is also a language setting for the custom field displayed name:

if(typeof(lang["customIndexTxt"])=="undefined" || lang["customIndexTxt"]=="") {
lang["customIndexTxt"] = "Custom field name";
}

The reason for the testing for undefined or blank above is just in case the user has set it in the language.

You can use the custom searchable field in the page by adding a lookup in the page or the editor.  On jobs there is a hidden tile that displays the  CUSTOM_INDEX field and can be shown and utilised like so in a plugin:

$("#job_tile_custom_index")
.show()
.click(function() {
window.open("https://www.my_external_app.com?id="+job_data["CUSTOM_INDEX"],"newwindow");
});

To save the CUSTOM_INDEX field in the relevant edit widget, using a custom plugin you can add a form element into the edit widget, for example like so:

// This adds the CUSTOM_INDEX field into the job edit widget
if(typeof($.custom.job_edit)!="undefined") {
// Redefine job_edit, move name to after telephone
$.widget("custom.job_edit", $.custom.job_edit, {
_init_main: function() {
// Call the old _init_main
this._super(arguments);
// Add an extra edit in the job edit
var table = this.default_disc.closest("table");
var tr = $("<tr>").appendTo( table);
$("<td>", { html: lang.customIndexTxt+ " :" }).appendTo(tr);
$("<input>", {
"name" : "custom_index", // Parameter to pass when saving
"class" : "data_cell",   // Setting class to data_cell tells HireHop it is a standard data field
"data-field" : "CUSTOM_INDEX", // Name of the field
"maxlength" : 45         // The CUSTOM_INDEX has a maximum length of 45 characters
})
.appendTo( $("<td>").appendTo(tr) );
// Change the memo height to compensate
this.job_edit_memo.height(110);
}
});
}

The CUSTOM_INDEX field is called xxx:custom_index in the document and is passed as a string into the document.

Global Custom Fields

Occasionally you might want to store a global counter, etc. for the whole company.  To read and store global custom fields use /php_functions/custom_fields_global_load.php and /php_functions/custom_fields_global_save.php.  Saving the data, you need to pass either a json string or json array:

$("#saving_dialog").dialog("open");
// This adds the CUSTOM_INDEX field into the job edit widget
$.ajax({
url: "/php_functions/custom_fields_global_save.php",
type: "post",
dataType: "json",
data: {
"fields":{"my_field":"any type of value"}
// or a json string
// "field":'{"my_field":"any type of value"}'
},
success: function(data)
{
$("#saving_dialog").dialog("close");
// HireHop reported an error
if(typeof(data.error) !== "undefined")
error_message(isNaN(parseInt(data.error)) ? data.error : lang.error[data.error]);
else
{
// All good, "data" is a javascript object (JSON) of all global custom fields
}
},
// Handle an http error
error: function(jqXHR, textStatus, errorThrown)
{
$("#saving_dialog").dialog("close");
error_message(lang.error[1]+" ("+errorThrown+").");
}
});

Posted in API