Ana içeriğe geç

Python Örneği

Flask kullanarak webhook sunucusu ve requests ile status update.

Kurulum

pip install flask requests

Webhook Sunucusu

import hmac
import hashlib
import json
import os
from flask import Flask, request, jsonify

app = Flask(__name__)

API_SECRET = os.getenv('API_SECRET', 'your-api-secret')


def verify_signature(payload: bytes, signature: str) -> bool:
    """HMAC-SHA256 imza doğrulama"""
    expected = hmac.new(
        API_SECRET.encode(), payload, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(signature, expected)


@app.route('/webhooks/new-order', methods=['POST'])
def new_order():
    """Yeni sipariş webhook handler"""
    # İmza doğrula (opsiyonel, geliştirme ortamında atlanabilir)
    sig = request.headers.get('X-MuditaPOS-Signature', '')
    if sig and not verify_signature(request.data, sig):
        return jsonify({'error': 'Geçersiz imza'}), 401

    order = request.json

    print('=' * 50)
    print('🆕 YENİ SİPARİŞ')
    print(f"  Platform    : {order.get('provider')}")
    print(f"  Sipariş ID  : {order.get('providerOrderId')}")
    print(f"  Müşteri     : {order.get('customerName')}")
    print(f"  Telefon     : {order.get('customerPhone')}")
    print(f"  Adres       : {order.get('customerAddress')}")
    print(f"  Toplam      : {order.get('totalAmount')} TL")
    print(f"  Ödeme       : {order.get('paymentMethod')}")
    print(f"  Ürün Sayısı : {len(order.get('items', []))}")
    print('=' * 50)

    for i, item in enumerate(order.get('items', []), 1):
        opts = ', '.join(o['name'] for o in item.get('options', []))
        print(f"  {i}. {item['name']} x{item['quantity']} = {item['totalPrice']} TL")
        if opts:
            print(f"     Ekstralar: {opts}")

    return jsonify({'status': 'received'})


@app.route('/webhooks/cancel-order', methods=['POST'])
def cancel_order():
    """İptal webhook handler"""
    data = request.json
    print(f"❌ İPTAL: {data.get('providerOrderId')} - {data.get('reason', '')}")
    return jsonify({'status': 'received'})


@app.route('/webhooks/order-status', methods=['POST'])
def order_status():
    """Durum güncelleme webhook handler"""
    data = request.json
    print(f"🔄 DURUM: {data.get('providerOrderId')}{data.get('newStatus')}")
    return jsonify({'status': 'received'})


if __name__ == '__main__':
    app.run(port=3001, debug=True)

Status Update Gönderme

import requests
import os

POS_API = os.getenv('POS_API_URL', 'https://stage.pos.muditakurye.com.tr')
INTERNAL_KEY = os.getenv('INTERNAL_API_KEY', 'your-internal-key')


def update_status(provider_order_id: str, platform: str, action: str, reason: str = ''):
    """Sipariş durumunu MuditaPOS'a bildir"""
    response = requests.post(
        f'{POS_API}/internal/orders/status',
        json={
            'providerOrderId': provider_order_id,
            'platform': platform,
            'action': action,
            'reason': reason,
        },
        headers={
            'Content-Type': 'application/json',
            'X-Internal-Api-Key': INTERNAL_KEY,
        },
        timeout=10,
    )

    data = response.json()
    print(f'📤 {action}{data}')
    return data


# Kullanım
if __name__ == '__main__':
    # Onayla
    update_status('getir-123', 'GETIR', 'VERIFY')

    # Hazırla
    update_status('getir-123', 'GETIR', 'PREPARE')

    # Teslim et
    update_status('getir-123', 'GETIR', 'DELIVER')

    # İptal
    update_status('ys-456', 'YEMEKSEPETI', 'CANCEL', 'Stok yok')