webhook接口:
<?php //秘钥(项目添加webhook时填写的秘钥文本,添加webhook必须是gogs类型) define('SECRET', ''); //合法IP(不添加则不验证) $ip_arr = ['']; /* * ****************************repository config start *************************************** */ //只对下边列出的git版本库以及指定分支生效 //格式: array('ssh_url'=>'版本库地址','branch'=>'分支名称','wwwroot'=>'部署路径')(版本库地址填写 ssh_url) $job_repository = [ 'ssh_url' => 'git@gogs.com:xxx/gogs_webhook.git', //ssh版本库地址,必填 'branch' => 'master', //需要更新的分支,必填 'wwwroot' => '/opt/gogs_webhook', //部署路径,必填 ]; $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : ''; //IP $signature = isset($_SERVER['HTTP_X_GOGS_SIGNATURE']) ? $_SERVER['HTTP_X_GOGS_SIGNATURE'] : ''; //签名 $event = isset($_SERVER['HTTP_X_GOGS_EVENT']) ? $_SERVER['HTTP_X_GOGS_EVENT'] : ''; //事件 if (empty($ip) || empty($signature) || empty($event)) { echo 'error 403'; exit(); } //"========================================webhook start========================================"; //获取json数据 $json_data = file_get_contents("php://input"); $data = json_decode($json_data, true); if (empty($data)) { echo '无效数据'; exit(); } $branch = @end(explode("/", $data['ref'])); //分支 $repository_url = $data['repository']['ssh_url']; //版本库地址(ssh_url) echo '地址: ' . $repository_url . ', 分支: ' . $branch . ', 事件: ' . $event; echo "RAW DATA: " . var_export($data, true); //验证签名 $re_sign = hash_hmac('sha256', $json_data, SECRET); if ($re_sign != $signature) { echo 'signature签名错误'; exit(); } if (!empty($ip_arr) && (empty($ip) || !in_array($ip, $ip_arr))) { echo '不合法IP'; exit(); } if (strtolower($event) != 'push') { echo '非push操作'; exit(); } //拼接cmd命令 $cmd = "cd {$job_repository['wwwroot']};git pull origin {$branch}"; //执行命令 $output = array(); exec($cmd, $output, $return_var); if ($return_var == 0) { write_log("success", $output); } else { write_log("cmd error status:{$return_var}", $output); } echo '执行结束';