webhooks_在本地开发时如何测试Webhooks

webhooks

by Stefan Doorn

斯蒂芬·多恩(Stefan Doorn)

在本地开发时如何测试Webhooks (How to test Webhooks when you’re developing locally)

Webhooks can be used by an external system for notifying your system about a certain event or update. Probably the most well known type is the one where a Payment Service Provider (PSP) informs your system about status updates of payments.

外部系统可以使用Webhooks来通知系统有关某个事件或更新的信息。 可能最著名的类型是付款服务提供商(PSP)通知您的系统有关付款状态更新的类型。

Often they come in the form where you listen on a predefined URL. For example http://example.com/webhooks/payment-update. Meanwhile the other system sends a POST request with a certain payload to that URL (for example a payment ID). As soon as the request comes in, you fetch the payment ID, ask the PSP for the latest status via their API, and update your database afterward.

通常,它们以您在预定义URL上侦听的形式出现。 例如http://example.com/webhooks/payment-update 。 同时,另一个系统将带有一定负载的POST请求发送到该URL(例如,付款ID)。 收到请求后,您将获取付款ID,通过其API向PSP询问最新状态,然后再更新数据库。

Other examples can be found in this excellent explanation about Webhooks. https://sendgrid.com/blog/whats-webhook/.

在有关Webhooks的出色解释中可以找到其他示例。 https://sendgrid.com/blog/whats-webhook/

Testing these webhooks goes fairly smoothly as long as the system is publicly accessible over the internet. This might be your production environment or a publicly accessible staging environment. It becomes harder when you are developing locally on your laptop or inside a Virtual Machine (VM, for example, a Vagrant box). In those cases, the local URL’s are not publicly accessible by the party sending the webhook. Also, monitoring the requests being sent around is be difficult, which might make development and debugging hard.

只要可以通过Internet公开访问该系统,这些Web钩子的测试就相当顺利。 这可能是您的生产环境或可公开访问的登台环境。 当您在笔记本电脑上或虚拟机(例如VM,例如Vagrant box)内部进行本地开发时,这会变得更加困难。 在这种情况下,发送Webhook的一方无法公开访问本地URL。 另外,监视发送的请求很困难,这可能会使开发和调试变得困难。

What will this example solve:

此示例将解决什么:

  • Testing webhooks from a local development environment, which is not accessible over the internet. It cannot be accessed by the service sending the data to the webhook from their servers.

    从本地开发环境测试Webhook,该环境无法通过Internet访问。 从服务器将数据发送到Webhook的服务无法访问它。
  • Monitor the requests and data being sent around, but also the response your application generates. This will allow easier debugging, and therefore a shorter development cycle.

    监视发送的请求和数据,以及应用程序生成的响应。 这将使调试更加容易,从而缩短开发周期。

Prerequisites:

先决条件:

  • Optional: in case you are developing using a Virtual Machine (VM), make sure it’s running and make sure the next steps are done in the VM.

    可选 :如果要使用虚拟机(VM)进行开发,请确保其正在运行,并确保在VM中完成了后续步骤。

  • For this tutorial, we assume you have a vhost defined at webhook.example.vagrant. I used a Vagrant VM for this tutorial, but you are free in choosing the name of your vhost.

    对于本教程,我们假设您在webhook.example.vagrant定义了一个虚拟主机。 我在本教程中使用的是Vagrant VM,但是您可以自由选择虚拟主机的名称。

  • Install ngrokby following the installation instructions. Inside a VM, I find the Node version of it also useful: https://www.npmjs.com/package/ngrok, but feel free to use other methods.

    按照安装说明安装ngrok 。 在VM内,我发现它的Node版本也很有用: https : //www.npmjs.com/package/ngrok ,但是随时可以使用其他方法。

I assume you don’t have SSL running in your environment, but if you do, feel free to replace port 80 with port 433 and http:// with https:// in the examples below.

我假设您的环境中没有运行SSL,但是如果您这样做,请在以下示例中随意将端口80替换为端口433,将http://替换为https://

使Webhook可测试 (Make the webhook testable)

Let’s assume the following example code. I’ll be using PHP, but read it as pseudo-code as I left some crucial parts out (for example API keys, input validation, etc.)

让我们假设以下示例代码。 我将使用PHP,但是当我遗漏了一些关键部分(例如API密钥,输入验证等)时,将其读为伪代码。

The first file: payment.php. This file creates a payment object and then registers it with the PSP. It then fetches the URL the customer needs to visit in order to pay and redirects the user to the customer in there.

第一个文件: payment.php 。 该文件创建付款对象,然后将其注册到PSP。 然后,它获取客户需要访问以进行支付的URL,并将用户重定向到那里的客户。

Note that the webhook.example.vagrant in this example is the local vhost we’ve defined for our development set-up. It’s not accessible from the outside world.

请注意,此示例中的webhook.example.vagrant是我们为开发设置定义的本地虚拟主机。 外界无法访问。

<?php
/*
 * This file creates a payment and tells the PSP what webhook URL to use for updates
 * After creating the payment, we get a URL to send the customer to in order to pay at the PSP
 */
$payment = [
    'order_id' => 123,
    'amount' => 25.00,
    'description' => 'Test payment',
    'redirect_url' => 'http://webhook.example.vagrant/redirect.php',
    'webhook_url' => 'http://webhook.example.vagrant/webhook.php',
];

$payment = $paymentProvider->createPayment($payment);
header("Location: " . $payment->getPaymentUrl());

Second file: webhook.php. This file waits to be called by the PSP to get notified about updates.

第二个文件: webhook.php 。 该文件等待PSP调用以获取有关更新的通知。

<?php
/*
 * This file gets called by the PSP and in the $_POST they submit an 'id'
 * We can use this ID to get the latest status from the PSP and update our internal systems afterward
 */
 
$paymentId = $_POST['id'];
$paymentInfo = $paymentProvider->getPayment($paymentId);
$status = $paymentInfo->getStatus();

// Perform actions in here to update your system
if ($status === 'paid') {
    ..
}
elseif ($status === 'cancelled') {
    ..
}

Our webhook URL is not accessible over the internet (remember: webhook.example.vagrant). Thus, the file webhook.php will never be called by the PSP. Your system will never get to know about the payment status. This ultimately leads to orders never being shipped to customers.

我们的webhook URL无法通过Internet访问(请记住: webhook.example.vagrant )。 因此,PSP将永远不会调用webhook.php文件。 您的系统永远不会了解付款状态。 最终导致订单永远不会交付给客户。

Luckily, ngrok can in solving this problem. ngrok describes itself as:

幸运的是, ngrok可以解决这个问题。 ngrok将自己描述为:

ngrok exposes local servers behind NATs and firewalls to the public internet over secure tunnels.
ngrok通过安全隧道将位于NAT和防火墙之后的本地服务器公开到公共Internet。

Let’s start a basic tunnel for our project. On your environment (either on your system or on the VM) run the following command:

让我们为项目启动一个基本隧道。 在您的环境(系统或VM上)上,运行以下命令:

ngrok http -host-header=rewrite webhook.example.vagrant:80

ngrok http -host-header=rewrite webhook.example.vagrant:80

Read about more configuration options in their documentation: https://ngrok.com/docs.

在其文档中了解更多配置选项: https : //ngrok.com/docs

A screen like this will come up:

这样的屏幕将会出现:

What did we just start? Basically, we instructed ngrok to start a tunnel to http://webhook.example.vagrant at port 80. This same URL can now be reached via http://39741ffc.ngrok.io or https://39741ffc.ngrok.io, They are publicly accessible over the internet by anyone that knows this URL.

我们刚刚开始了什么? 基本上,我们指示ngrok在端口80上启动到http://webhook.example.vagrant的隧道。现在可以通过http://39741ffc.ngrok.iohttps://39741ffc.ngrok.io到达相同的URL。 任何知道此URL的人都可以通过Internet公开访问它们。

Note that you get both HTTP and HTTPS available out of the box. The documentation gives examples of how to restrict this to HTTPS only: https://ngrok.com/docs#bind-tls.

请注意 ,您可以立即使用HTTP和HTTPS。 该文档提供了有关如何仅将此限制为HTTPS的示例: https : //ngrok.com/docs#bind-tls

So, how do we make our webhook work now? Update payment.php to the following code:

那么,我们如何使我们的网络挂钩现在工作? 将payment.php更新为以下代码:

<?php
/*
 * This file creates a payment and tells the PSP what webhook URL to use for updates
 * After creating the payment, we get a URL to send the customer to in order to pay at the PSP
 */
$payment = [
    'order_id' => 123,
    'amount' => 25.00,
    'description' => 'Test payment',
    'redirect_url' => 'http://webhook.example.vagrant/redirect.php',
    'webhook_url' => 'https://39741ffc.ngrok.io/webhook.php',
];

$payment = $paymentProvider->createPayment($payment);
header("Location: " . $payment->getPaymentUrl());

Now, we told the PSP to call the tunnel URL over HTTPS. ngrok will make sure your internal URL get’s called with an unmodified payload, as soon as the PSP calls the webhook via the tunnel.

现在,我们告诉PSP通过HTTPS调用隧道URL。 一旦PSP通过隧道调用webhook, ngrok将确保使用未经修改的有效负载调用内部URL。

如何监控对网络挂钩的呼叫? (How to monitor calls to the webhook?)

The screenshot you’ve seen above gives an overview of the calls being made to the tunnel host. This data is rather limited. Fortunately, ngrok offers a very nice dashboard, which allows you to inspect all calls:

您在上面看到的屏幕快照概述了对隧道主机的调用。 该数据是相当有限的。 幸运的是, ngrok提供了一个非常不错的仪表板,可让您检查所有呼叫:

I won’t go into this very deep because it’s self-explanatory as soon as you have it running. Therefore I will explain how to access it on the Vagrant box as it doesn’t work out of the box.

我不会深入探讨这个问题,因为一旦运行它就可以自解释。 因此,我将在“无业游民”盒子中解释如何访问它,因为它不能直接使用。

The dashboard will allow you to see all the calls, their status codes, the headers and data being sent around. You will also see the response your application generated.

仪表板将允许您查看所有呼叫,其状态代码,标题和正在发送的数据。 您还将看到您的应用程序生成的响应。

Another neat feature of the dashboard is that it allows you to replay a certain call. Let’s say your webhook code ran into a fatal error, it would be tedious to start a new payment and wait for the webhook to be called. Replaying the previous call makes your development process way faster.

仪表板的另一个简洁功能是允许您重播特定呼叫。 假设您的Webhook代码遇到一个致命错误,开始新的付款并等待该Webhook被调用很繁琐。 重播上一个调用可以使您的开发过程更快。

The dashboard by default is accessible at http://localhost:4040.

默认情况下,该仪表板可从http:// localhost:4040访问。

VM中的仪表板 (Dashboard in a VM)

In order to make this work inside a VM, you have to perform some additional steps:

为了使此功能在VM中起作用,您必须执行一些其他步骤:

First, make sure the VM can be accessed on port 4040. Then, create a file inside the VM holding this configuration:

首先,确保可以在端口4040上访问VM。然后,在包含此配置的VM内部创建一个文件:

web_addr: 0.0.0.0:4040

web_addr: 0.0.0.0:4040

Now, kill the ngrok process that’s still running and start it with this slightly adjusted command:

现在,杀死仍在运行的ngrok进程,并使用以下稍微调整的命令启动它:

ngrok http -config=/path/to/config/ngrok.conf -host-header=rewrite webhook.example.vagrant:80

ngrok http -config=/path/to/config/ngrok.conf -host-header=rewrite webhook.example.vagrant:80

You will get a screen looking similar to the previous screenshot though the ID’s have changed. The previous URL doesn’t work anymore, but you got a new URL. Also, the Web Interface URL got changed:

尽管ID已更改,但您将获得一个类似于上一个屏幕截图的屏幕。 以前的URL不再起作用,但是您获得了一个新URL。 此外, Web Interface URL也已更改:

Now direct your browser to http://webhook.example.vagrant:4040 to access the dashboard. Also, make a call to https://e65642b5.ngrok.io/webhook.php.This will probably result in an error in your browser, but the dashboard should show the request being made.

现在,将浏览器定向到http://webhook.example.vagrant:4040以访问仪表板。 另外,拨打https://e65642b5.ngrok.io/webhook.php 这可能会导致浏览器出错,但是仪表板应显示正在发出的请求。

结束语 (Final remarks)

The examples above are pseudo-code. The reason is that every external system uses webhooks in a different way. I tried to give an example based on a fictive PSP implementation, as probably many developers have to deal with payments at some moment.

上面的示例是伪代码。 原因是每个外部系统都以不同的方式使用webhooks。 我试图给出一个基于虚拟PSP实现的示例,因为可能很多开发人员有时不得不处理付款。

Please be aware that your webhook URL can also be used by others with bad intentions. Make sure to validate any input being sent to it.

请注意,您的Webhook URL也可能被恶意使用。 确保验证发送给它的所有输入。

Preferably also add a token to the URL which is unique for each payment. This token must only be known by your system and the system sending the webhook.

最好还向URL添加一个令牌,该令牌对于每次付款都是唯一的。 只有系统和发送Webhook的系统才能知道此令牌。

Good luck testing and debugging your webhooks!

祝您好运,测试和调试您的Webhooks!

Note: I haven’t tested this tutorial on Docker. However, this Docker container looks like a good starting point and includes clear instructions. https://github.com/wernight/docker-ngrok.

注意:我尚未在Docker上测试过本教程。 但是,此Docker容器看起来是一个很好的起点,并且包含明确的说明。 https://github.com/wernight/docker-ngrok

Stefan Doorn

斯蒂芬·多恩

https://github.com/stefandoornhttps://twitter.com/stefan_doornhttps://www.linkedin.com/in/stefandoorn

https://github.com/stefandoorn https://twitter.com/stefan_doorn https://www.linkedin.com/in/stefandoorn

翻译自: https://www.freecodecamp.org/news/testing-webhooks-while-using-vagrant-for-development-98b5f3bedb1d/

webhooks

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值