Run code when a file arrives
Run your own code whenever a file arrives, whichever way it came in: the browser, an agent, the API, email or SFTP. This guide posts each new file to a Slack channel.
-
Write an endpoint that checks the signature
drop.media signs every request with the endpoint's secret. Check the signature against the raw body before you parse it, and ignore old timestamps so a captured request can't be replayed.
import crypto from 'node:crypto'; import express from 'express'; const app = express(); const secret = process.env.DROP_WEBHOOK_SECRET; // whsec_… // express.raw keeps the body as received, which the signature is computed over. app.post('/webhooks/drop', express.raw({ type: 'application/json' }), async (req, res) => { const match = /^t=(\d+),v1=([0-9a-f]{64})$/.exec(req.get('Drop-Signature') ?? ''); if (!match) return res.sendStatus(400); const [, t, sig] = match; const expected = crypto.createHmac('sha256', secret).update(`${t}.${req.body}`).digest('hex'); const fresh = Math.abs(Date.now() / 1000 - Number(t)) < 300; if (!fresh || !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(sig))) return res.sendStatus(400); const event = JSON.parse(req.body); if (event.type === 'file.created') { const { name, url, source } = event.data.file; await fetch(process.env.SLACK_WEBHOOK_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: `New file from ${source}: <${url}|${name}>` }), }); } res.sendStatus(204); }); app.listen(3000);import hashlib, hmac, os, time import requests from flask import Flask, abort, request app = Flask(__name__) secret = os.environ["DROP_WEBHOOK_SECRET"].encode() # whsec_… def drop_webhook(): raw = request.get_data() # the body as received, which the signature is computed over parts = dict(p.split("=", 1) for p in request.headers.get("Drop-Signature", "").split(",") if "=" in p) t, sig = parts.get("t", ""), parts.get("v1", "") expected = hmac.new(secret, f"{t}.".encode() + raw, hashlib.sha256).hexdigest() if not t.isdigit() or not hmac.compare_digest(expected, sig) or abs(time.time() - int(t)) > 300: abort(400) event = request.get_json() if event["type"] == "file.created": f = event["data"]["file"] requests.post(os.environ["SLACK_WEBHOOK_URL"], json={"text": f"New file from {f['source']}: <{f['url']}|{f['name']}>"}) return "", 204package main import ( "bytes" "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "fmt" "io" "net/http" "os" "time" ) func main() { secret := os.Getenv("DROP_WEBHOOK_SECRET") // whsec_… http.HandleFunc("POST /webhooks/drop", func(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) // the body as received, which the signature is computed over var t int64 var sig string fmt.Sscanf(r.Header.Get("Drop-Signature"), "t=%d,v1=%s", &t, &sig) mac := hmac.New(sha256.New, []byte(secret)) fmt.Fprintf(mac, "%d.%s", t, body) expected := hex.EncodeToString(mac.Sum(nil)) age := time.Since(time.Unix(t, 0)) if !hmac.Equal([]byte(expected), []byte(sig)) || age > 5*time.Minute || age < -5*time.Minute { http.Error(w, "bad signature", http.StatusBadRequest) return } var event struct { Type string Data struct { File struct{ Name, URL, Source string } } } json.Unmarshal(body, &event) if event.Type == "file.created" { f := event.Data.File msg, _ := json.Marshal(map[string]string{"text": fmt.Sprintf("New file from %s: <%s|%s>", f.Source, f.URL, f.Name)}) http.Post(os.Getenv("SLACK_WEBHOOK_URL"), "application/json", bytes.NewReader(msg)) } w.WriteHeader(http.StatusNoContent) }) http.ListenAndServe(":3000", nil) }require "json" require "net/http" require "openssl" require "sinatra" SECRET = ENV.fetch("DROP_WEBHOOK_SECRET") # whsec_… post "/webhooks/drop" do raw = request.body.read # the body as received, which the signature is computed over t, sig = request.env["HTTP_DROP_SIGNATURE"].to_s.match(/\At=(\d+),v1=(\h{64})\z/)&.captures halt 400 unless t expected = OpenSSL::HMAC.hexdigest("SHA256", SECRET, "#{t}.#{raw}") halt 400 unless OpenSSL.fixed_length_secure_compare(expected, sig) && (Time.now.to_i - t.to_i).abs < 300 event = JSON.parse(raw) if event["type"] == "file.created" file = event.dig("data", "file") text = "New file from #{file["source"]}: <#{file["url"]}|#{file["name"]}>" Net::HTTP.post(URI(ENV.fetch("SLACK_WEBHOOK_URL")), { text: text }.to_json, "Content-Type" => "application/json") end 204 end// Laravel, in routes/web.php. Exclude the route from CSRF protection. use Illuminate\Http\Request; use Illuminate\Support\Facades\Http; Route::post('/webhooks/drop', function (Request $request) { $raw = $request->getContent(); // the body as received, which the signature is computed over if (! preg_match('/^t=(\d+),v1=([0-9a-f]{64})$/', (string) $request->header('Drop-Signature'), $m)) { abort(400); } $expected = hash_hmac('sha256', $m[1].'.'.$raw, config('services.drop.webhook_secret')); abort_unless(hash_equals($expected, $m[2]) && abs(time() - (int) $m[1]) < 300, 400); $event = json_decode($raw, true); if ($event['type'] === 'file.created') { $file = $event['data']['file']; Http::post(config('services.slack.webhook_url'), [ 'text' => "New file from {$file['source']}: <{$file['url']}|{$file['name']}>", ]); } return response()->noContent(); }); -
Add the endpoint
On the Webhooks page in the app, add your endpoint's URL (it must be
https://and reachable from the internet) and choosefile.created. Copy its signing secret intoDROP_WEBHOOK_SECRET. -
Send a test event
Send test event on the endpoint's page sends a
pingstraight away and shows the response. Then upload a file any way you like and watch it arrive in Slack.
Make it reliable
- Reply fast. Answer with any
2xxwithin 10 seconds, and do slow work in the background. - Expect retries. A failed delivery is retried for about two days, so the same event can arrive twice. The
Drop-Deliveryheader is the event's id and stays the same on every retry: store it and skip ones you've seen. - Trace anything. The event id is also in Logs, which shows what caused the event and every delivery of it.
The full list of events and headers is in the Webhooks reference.