Les événements vous permettent de recevoir des notifications en temps réel de GoCardless lorsque des opérations sont effectuées sur votre compte, afin que vous puissiez prendre des mesures automatisées en conséquence, par exemple :
- si un paiement échoue car les fonds ne sont pas suffisants, le réessayer automatiquement ;
- si un client final annule son mandat auprès de la banque, suspendre son compte ;
- si l'abonnement d'un client final génère un nouveau paiement, enregistrer ce paiement sur son compte.
Il existe deux moyens de recevoir les informations d'un événement :
Webhooks : un webhook est une demande que GoCardless envoie à votre serveur pour vous signaler un événement.
Le point de terminaison des événements : vous pouvez répertorier les événements directement depuis leur point de terminaison si vous préférez extraire les informations vous-même. Ce moyen peut être préférable si vous allez traiter des volumes importants d'événements.
Traitement des événements en utilisant des webhooks
Rendre l'hôte local accessible sur Internet avec ngrok
Pour commencer à utiliser les webhooks, votre code doit être accessible sur Internet pour que GoCardless puisse y accéder à l'aide de requêtes HTTP. Si vous travaillez en local, le moyen le plus simple est d'utiliser ngrok.
Téléchargez-le et suivez les instructions sur la page pour l'installer (vous devez décompresser le fichier archivé, puis rendre le fichier binairengrok disponible dans votre CHEMIN D'ACCÈS).
À présent, il vous suffit d'exécuter ngrok http <port>
, où <port> est le port sur lequel votre serveur web est exécuté (par exemple, ngrok http 8000
si vous l'exécutez sur le port 8000).
Deux liens de redirection vers localhost:8000 s'affichent. Sélectionnez l'URL qui commence par https et copiez-la dans votre presse-papiers.
Dans un environnement sandbox, vous pouvez utiliser une URL HTTP pour vos webhooks, mais pour une mise en service, le point de terminaison doit être sécurisé avec le protocole HTTPS.
Ajouter une URL de webhook dans le tableau de bord GoCardless
Pour commencer à recevoir des webhooks, vous devez ajouter un point de terminaison de webhook depuis votre tableau de bord ici.
Entrez simplement l'URL HTTPS précédente et ajoutez le chemin d'accès du gestionnaire de webhooks, donnez un nom à votre point de terminaison, puis cliquez sur « Créer un point de terminaison de webhook ». Ensuite, cliquez sur le nouveau point de terminaison dans la liste et copiez le secret dans votre presse-papiers.
Créer un gestionnaire de webhooks
Les webhooks sont des requêtes POST HTTP envoyées à l'URL que vous avez fournie, avec un corps JSON.
La première étape à effectuer lorsque vous recevez un webhook consiste à vérifier sa signature - cela garantit qu'il provient effectivement de GoCardless et qu'il n'a pas été falsifié. Une signature est fournie dans l'en-tête Webhook-Signature de la requête. Il nous suffit de calculer la signature nous-mêmes avec le corps JSON de la requête POST et le secret du point de terminaison du webhook (que nous avons copié auparavant) et de la comparer à celle de l'en-tête.
Si elles correspondent, le webhook est authentique, car seuls vous et GoCardless connaissez le secret. Il est important de protéger le secret et de le modifier régulièrement en utilisant le tableau de bord.
Lorsque la signature a été authentifiée, vous pouvez alors envoyer une réponse 2xx avant de traiter les données utiles JSON.
Veuillez noter que, si vous n'envoyez pas de réponse 2xx dans un délai de 10 secondes, le webhook échouera et nous le tenterons à nouveau aux intervalles indiqués ici. Il est donc important de traiter les webhooks de manière asynchrone pour éviter l'expiration du délai si vous recevez plusieurs événements à la fois (envoyez une réponse 2xx avant de traiter le webhook).
Une fois que vous avez effectué les opérations souhaitées pour un événement, nous vous recommandons d'effectuer un enregistrement pour éviter de le traiter accidentellement deux fois.
Pour des exemples de code détaillés sur la procédure de vérification de la signature, reportez-vous au lien disponible ici.
Tester votre gestionnaire de webhooks
Dans le tableau de bord, la fonctionnalité « Envoyer un webhook de test » permet de démarrer facilement avec les webhooks.
Sélectionnez le point de terminaison de webhook que vous avez créé auparavant, définissez le type de ressource « mandats » et l'action sur « annulé ». Vous pouvez indiquer la raison et les détails de l'événement. Ensuite, cliquez sur « Envoyer un webhook de test ».
Maintenant, actualisez la page. Généralement, le webhook s'affiche directement, mais il peut être parfois nécessaire d'actualiser la page plusieurs fois. Nous enverrons une requête à votre point de terminaison, et votre webhook apparaîtra dans la liste - cliquez dessus. Si tout fonctionne correctement, le code de réponse 200 OK s'affichera.
Nouvelles tentatives / échecs de webhooks
L'envoi des webhooks peut échouer pour différentes raisons, telles que les suivantes :
- Délais d'attente : nous n'avons pas reçu de réponse 2xx dans un délai de 10 secondes après l'envoi du webhook.
- Accès non autorisé : une autorisation du serveur est requise, mais une authentification non valide a été fournie.
- La requête a été redirigée : nous ne suivons pas les redirections HTTP, et nous les traitons donc comme des échecs de webhook.
Si un webhook échoue, nous le tenterons à nouveau jusqu'à 8 fois à des intervalles croissants, par exemple 1 minute, 2 minutes, 10 minutes, etc.
Traiter les événements au sein des webhooks
Un webhook peut contenir plusieurs événements, et chacun d'entre eux comporte un paramètre resource_type (qui nous indique pour quel type de ressource est l'événement, par exemple « paiements » ou « mandats »), une action (qui nous indique ce qui est arrivé à la ressource, par exemple l'action « annulé » pour un mandat) et des détails (spécifiant pourquoi l'événement s'est produit).
Vous pouvez consulter la liste des combinaisons possibles dans les documents de référence et voir un exemple de gestionnaire d'événements ici.
Vous pouvez ajouter la prise en charge d'autant de paramètres source_types
et d'actions que vous le souhaitez, et utiliser toutes les autres données que nous vous fournissons avec les événements.
Déclencher des webhooks
Lorsque vous créez votre intégration, vous voulez recevoir des webhooks réalistes afin de tester la façon dont votre intégration répond.
Vous pouvez déclencher des webhooks à l'aide de nos simulateurs de scénario ou de l'outil « Envoyer un webhook de test ». Cliquez simplement sur « Envoyer un webhook de test » sur la page « Développeurs » dans votre tableau de bord.
Pour pouvoir utiliser l'outil « Envoyer un webhook de test », vous devez au préalable configurer un point de terminaison de webhook. Cliquez sur « Créer » puis sur « Points de terminaison de webhook » sur la page « Développeurs » dans votre tableau de bord. Si vous avez créé des applications, leurs points de terminaison de webhook seront disponibles également.
Vous pourrez ensuite personnaliser votre webhook. Tout d'abord, choisissez vos points de terminaison de webhook, puis définissez le type de ressource, l'action, les détails de l'événement et l'identifiant associé.
Dans votre code, vous allez probablement utiliser l'identifiant pour localiser les enregistrements dans votre base de données et prendre les mesures appropriées en fonction du webhook.
Cliquez sur « Envoyer un webhook de test ». Nous enverrons alors le webhook au point de terminaison que vous avez choisi, généralement au bout de quelques secondes.
Actualisez la page, et le webhook que nous venons d'envoyer s'affichera dans la liste de vos webhooks.
Cliquez sur un webhook pour afficher l'intégralité de la requête et votre réponse. Ceci est très utile à des fins de débogage.
Vous pouvez renvoyer un webhook que vous avez déjà envoyé en le sélectionnant dans la liste, puis en cliquant sur « Réessayer » dans le coin supérieur droit.
Traiter les événements en utilisant leur point de terminaison
Une alternative aux webhooks consiste à extraire les informations directement depuis le point de terminaison des événements.
Cette méthode est souvent utilisée car elle offre un contrôle accru sur le traitement des événements, et elle permet d'éliminer les aspects complexes liés aux échecs / nouvelles tentatives de webhook.
Elle implique d'appeler la liste des événements à certains moments de la journée, en envoyant le paramètre created_at[gt] à la liste des événements créés depuis votre dernière interrogation.
Vous pouvez également choisir d'extraire / traiter des événements spécifiques en utilisant les paramètres répertoriés ici. Par exemple, pour ne recevoir que les événements de mandat annulé, vous enverriez une requête similaire à la suivante :
GET https://api-sandbox.gocardless.com/events?action=cancelled&resource_type=mandate HTTP/1.1
Notez également que la majorité des événements sont créés lorsque nous recevons (entre 8 h et 11 h, heure d'été britannique) et envoyons (entre 15 h et 18 heures, heure d'été britannique) les rapports à la banque. Nous recommandons donc d'envoyer une requête au point de terminaison vers midi, puis dans la soirée et à d'autres périodes souhaitées.