پشتیار
پشتیار
ابزارها و وب‌هوک‌ها

پیاده‌سازی سرور وب‌هوک (نمونه کد)

پیاده‌سازی سرور وب‌هوک کامل در Python FastAPI, Go Fiber و Node.js Express

در این راهنما، پیاده‌سازی سرور دریافت وب‌هوک در ۳ فریم‌ورک محبوب آورده شده است. تب مورد نظر خود را انتخاب فرمایید:

from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel
from typing import Dict, Any, Optional

app = FastAPI(title="Poshtyar Webhook Server")

# توکن امنیتی ست شده در پنل پشتیار
AUTH_SECRET = "secret_token_123456"

class WebhookPayload(BaseModel):
    call_id: str
    caller_number: str
    operator_id: str
    arguments: Dict[str, Any]

@app.post("/api/v1/tools/order-lookup")
async def lookup_order(
    payload: WebhookPayload,
    x_internal_token: Optional[str] = Header(None)
):
    # ۱. اعتبارسنجی هدر امنیتی
    if x_internal_token != AUTH_SECRET:
        raise HTTPException(status_code=401, detail="Unauthorized token")
    
    order_id = payload.arguments.get("order_id")
    print(f"تماس {payload.call_id} از شماره {payload.caller_number} برای سفارش {order_id}")
    
    # ۲. استعلام از دیتابیس
    if order_id == "4920":
        return {
            "success": True,
            "result": {
                "order_id": order_id,
                "status": "ارسال شده با تیپاکس",
                "tracking_code": "981240",
                "delivery_date": "فردا ظهر"
            }
        }
    else:
        return {
            "success": False,
            "error": "سفارش مورد نظر یافت نشد"
        }
package main

import (
	"github.com/gofiber/fiber/v2"
)

type WebhookRequest struct {
	CallID       string                 `json:"call_id"`
	CallerNumber string                 `json:"caller_number"`
	OperatorID   string                 `json:"operator_id"`
	Arguments    map[string]interface{} `json:"arguments"`
}

func main() {
	app := fiber.New()

	app.Post("/api/v1/tools/order-lookup", func(c *fiber.Ctx) error {
		// اعتبارسنجی هدر امنیتی
		token := c.Get("X-INTERNAL-TOKEN")
		if token != "secret_token_123456" {
			return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{
				"error": "Unauthorized",
			})
		}

		var req WebhookRequest
		if err := c.BodyParser(&req); err != nil {
			return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
				"error": "Invalid JSON body",
			})
		}

		orderID, _ := req.Arguments["order_id"].(string)

		if orderID == "4920" {
			return c.JSON(fiber.Map{
				"success": true,
				"result": fiber.Map{
					"order_id":      orderID,
					"status":        "ارسال شده با پست پیشتاز",
					"tracking_code": "IR88990011",
				},
			})
		}

		return c.JSON(fiber.Map{
			"success": false,
			"error":   "سفارشی با این مشخصات یافت نشد",
		})
	})

	app.Listen(":8080")
}
const express = require('express');
const app = express();

app.use(express.json());

const WEBHOOK_SECRET = "secret_token_123456";

app.post('/api/v1/tools/order-lookup', (req, res) => {
  const token = req.headers['x-internal-token'];
  if (token !== WEBHOOK_SECRET) {
    return res.status(401).json({ error: 'Unauthorized' });
  }

  const { call_id, caller_number, arguments: args } = req.body;
  const orderId = args?.order_id;

  if (orderId === '4920') {
    return res.json({
      success: true,
      result: {
        order_id: orderId,
        status: 'آماده تحویل به پیک',
        buyer_name: 'آقای کریمی',
      },
    });
  }

  return res.json({
    success: false,
    error: 'سفارش یافت نشد',
  });
});

app.listen(3000, () => {
  console.log('Webhook server running on port 3000');
});