Xin chào ! Nếu đây là lần đầu tiên bạn đến với diễn đàn, xin vui lòng danh ra một phút bấm vào đây để đăng kí và tham gia thảo luận cùng VnPro.
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Hướng dẫn tạo Webhook bằng Azure Function - Triển khai serverless backend nhanh chóng trong 5 phút

    1. Chuẩn bị môi trường

    Trước khi tạo webhook thông qua Azure Function, cần chuẩn bị như sau:
    • Tài khoản Azure
    • Azure Function App (chạy runtime Python hoặc Node.js)
    • Visual Studio Code (hoặc Azure Portal)
    • Postman để test request

    2. Tạo Function App cục bộ

    2.1. Khởi tạo project Function
    Code:
    [INDENT][FONT=Courier New]mkdir webhook-demo
    cd webhook-demo
    func init --worker-runtime python --python[/FONT][/INDENT]

    Lệnh trên tạo project Function với runtime Python.
    Cấu trúc thư mục sau khi tạo:
    Code:
    [INDENT][FONT=Courier New]webhook-demo/
    ├── host.json
    ├── local.settings.json
    └── HttpTrigger1/[/FONT][/INDENT][INDENT=2][FONT=Courier New]├── __init__.py
    └── function.json[/FONT][/INDENT]

    2.2. Tạo một function mới

    Code:
    [FONT=Courier New]func new[/FONT]
    Chọn:
    • Template: HTTP Trigger
    • Function name: webhook_handler
    • Authorization level: Anonymous (để test public webhook dễ hơn)

    3. Viết logic webhook trong Python

    Mở file __init__.py trong thư mục webhook_handler và thay nội dung bằng:

    Code:
    [FONT=Courier New]import logging
    import json
    import azure.functions as func
    
    def main(req: func.HttpRequest) -> func.HttpResponse:[/FONT][INDENT][FONT=Courier New]logging.info('Webhook function triggered.')[/FONT][/INDENT][INDENT][FONT=Courier New]try:[/FONT][/INDENT][INDENT=2][FONT=Courier New]body = req.get_json()
    logging.info(f"Received payload: {json.dumps(body)}")
    
    # === Thực hiện xử lý tùy theo mục đích webhook ===
    # Ví dụ: lưu log, gọi API khác, hoặc phản hồi lại
    event_name = body.get("event_name", "undefined")
    user_id = body.get("user_id", "unknown")
    
    message = f"Webhook nhận thành công! Sự kiện: {event_name}, User ID: {user_id}"
    return func.HttpResponse(message, status_code=200)[/FONT][/INDENT][INDENT]
    [FONT=Courier New]except ValueError:[/FONT][/INDENT][INDENT=2][FONT=Courier New]return func.HttpResponse("Invalid JSON payload", status_code=400)​[/FONT][/INDENT]
    3.1. Cấu hình function.json
    Đảm bảo file function.json trông như sau:
    Code:
    [FONT=Courier New]{[/FONT][INDENT][FONT=Courier New]"bindings": [
    {[/FONT][/INDENT][INDENT=2][FONT=Courier New]"authLevel": "anonymous",
    "type": "httpTrigger",
    "direction": "in",
    "name": "req",
    "methods": [ "post", "get" ][/FONT][/INDENT][INDENT][FONT=Courier New]},
    {[/FONT][/INDENT][INDENT=2][FONT=Courier New]"type": "http",
    "direction": "out",
    "name": "$return"[/FONT][/INDENT][INDENT][FONT=Courier New]}
    ][/FONT][/INDENT]
     [FONT=Courier New]}[/FONT]

    4. Chạy và test webhook cục bộ

    4.1. Chạy Function
    Code:
    [INDENT][FONT=Courier New]func start[/FONT][/INDENT]
    Nếu thành công, bạn sẽ thấy log:
    Code:
    [INDENT][FONT=Courier New]Functions:[/FONT][/INDENT][INDENT=2][FONT=Courier New]webhook_handler: [POST] http://localhost:7071/api/webhook_handler​[/FONT][/INDENT]
    4.2. Test bằng Postman hoặc cURL
    Code:
    [INDENT][FONT=Courier New]curl -X POST http://localhost:7071/api/webhook_handler \
    -H "Content-Type: application/json" \
    -d '{"event_name": "user_send_text", "user_id": "12345"}'​[/FONT][/INDENT]
    Kết quả mong đợi:
    Code:
    [INDENT][FONT=Courier New]Webhook nhận thành công! Sự kiện: user_send_text, User ID: 12345[/FONT][/INDENT]

    5. Deploy lên Azure

    5.1. Đăng nhập và tạo Function App
    Code:
    [INDENT][FONT=Courier New]az login
    az functionapp create --name webhook-demo-func \
    --resource-group MyResourceGroup \
    --consumption-plan-location southeastasia \
    --runtime python \
    --runtime-version 3.10 \
    --functions-version 4 \
    --os-type linux \
    --storage-account mystorage123​[/FONT][/INDENT]
    Chú ý đổi webhook-demo-func, MyResourceGroup, và mystorage123 theo tên của bạn.
    5.2. Deploy code lên Azure
    Code:
    [INDENT][FONT=Courier New]func azure functionapp publish webhook-demo-func[/FONT][/INDENT]
    Khi hoàn tất, bạn sẽ nhận được endpoint công khai, ví dụ:
    https://webhook-demo-func.azurewebsites.net/api/webhook_handler

    6. Kiểm thử webhook online
    Dùng URL public đó để test:
    Code:
    [INDENT][FONT=Courier New]curl -X POST https://webhook-demo-func.azurewebsites.net/api/webhook_handler \
    -H "Content-Type: application/json" \
    -d '{"event_name": "order_created", "user_id": "VNPRO123"}'[/FONT][/INDENT]
    Kết quả:
    Webhook nhận thành công! Sự kiện: order_created, User ID: VNPRO123

    7. Bảo mật webhook
    Webhook công khai cần bảo vệ khỏi truy cập trái phép. Một số cách phổ biến:
    7.1. Sử dụng API Key
    • Trong function.json, thay authLevel từ "anonymous" → "function".
    • Azure sẽ tạo ra một Function Key trong tab “Manage”.
    • Khi gọi webhook, thêm query:
      ?code=<your_function_key>
    7.2. Xác thực chữ ký (HMAC)
    Thêm mã hash để xác nhận request đến từ bên tin cậy:
    Code:
    [INDENT][FONT=Courier New]import hmac
    import hashlib
    
    secret = "MY_SECRET_KEY"
    signature = req.headers.get("X-Signature", "")
    
    expected = hmac.new(secret.encode(), req.get_body(), hashlib.sha256).hexdigest()
    
    if not hmac.compare_digest(expected, signature):
    return func.HttpResponse("Invalid signature", status_code=401)​[/FONT][/INDENT]

    8. Theo dõi và ghi log

    Azure cung cấp Application Insights để giám sát:
    • Logs, Exception, Latency
    • Biểu đồ request/response
    • Truy vấn KQL để xem lịch sử webhook call
    Bật bằng Azure Portal → Function App → “Application Insights” → Enable.
    9. Ứng dụng thực tế

    Bạn có thể dùng webhook này cho:
    • Chatbot Zalo OA → nhận tin nhắn và forward sang API khác
    • SiteSpeakAI → xử lý event conversation
    • GitHub → tự động build/deploy khi push code
    • Payment Gateway (Stripe, Momo) → nhận callback khi giao dịch thành công

    10. Tổng kết

    Với Azure Function, bạn chỉ cần vài dòng code là đã có thể dựng một webhook hoàn chỉnh:
    • Không cần server vật lý
    • Tự động scale theo traffic
    • Dễ dàng bảo mật và giám sát
    Webhook kiểu serverless này đặc biệt phù hợp cho các dự án chatbot, automation hoặc tích hợp event-driven.
Working...
X