简介
WebHook是代码库服务商提供的一个服务,简单来说就是当你push代码到远程仓库后,服务商提供的服务进行事件监听,接收到事件后,服务商通知客户端进行处理,自动部署代码或者邮件通知。
使用WebHook
下面以码云为服务商为例。
1. 配置WebHook
- 登录码云
- 进入仓库管理
- 配置WebHook,添加回调地址,验签配置等信息
2.编写回调程序
class HookHandle
{
private $secret = ""; // 秘钥
private $algorithm = ""; // 哈希算法
public function __construct($secret, $algorithm = "sha256") {
$this->secret = $secret;
$this->algorithm = $algorithm;
}
/**
* @return bool
*/
private function verifySign()
{
$row = json_decode(file_get_contents("php://input"), true);
if (empty($row)) {
return false;
}
$timestamp = isset($row['timestamp']) ? $row['timestamp'] : '';
$getSign = isset($row['sign']) ? $row['sign'] : '';
if (empty($timestamp) || empty($getSign)) {
return false;
}
$hashStr = "{$timestamp}\n{$this->secret}";
$sign = base64_encode(hash_hmac($this->algorithm, $hashStr, $this->secret, true));
if ($sign == $getSign) {
return true;
}
return false;
}
/**
* 自动部署代码
* @param string $shellDir 项目路径
* @return bool
*/
public function execShell($shellDir)
{
if (!$this->verifySign()) {
return false;
}
if (empty($shellDir)) {
return false;
}
if (!is_dir($shellDir)) {
return false;
}
$logFile = $shellDir . "/hook.log";
shell_exec("cd {$shellDir} && git pull >> {$logFile} 2>&1"); // 需要修改 php.ini 配置
return true;
}
}
$hook = new HookHandle("secret");
if ($hook->execShell("projectPath")) {
echo "success";
} else {
echo "fail";
}
安全问题
由于回调地址是公网可访问地址,担心受到攻击,或者发送虚假信息到客户端。可以采用以下方法。
- 签名验证
- 只针对对应的域名或ip处理请求
注意的问题
由于服务商会向客户端发送大量的请求阻塞应用,需要确保客户端的服务稳定、正常。
- 本文链接:http://codersam.cn/2020/08/21/WebHook/
- 版权声明:本博客所有文章除特别声明外,均默认采用 许可协议。