webhook.py 2.62 KB
import hmac
import hashlib
import base64
from flask import Blueprint, request, jsonify, current_app
from config import Config
from middleware.hmac_validator import verify_webhook_hmac

# 创建Webhook蓝图
webhook_bp = Blueprint('webhook', __name__, url_prefix='/webhook')

@webhook_bp.route('/shoplazza', methods=['POST'])
def shoplazza_webhook():
    """
    处理Shoplazza Webhook
    """
    # 获取HMAC签名头
    hmac_header = request.headers.get('X-Shoplazza-Hmac-Sha256')
    if not hmac_header:
        return jsonify({'error': 'Missing HMAC header'}), 400
    
    # 获取原始数据
    data = request.get_data()
    
    # 验证Webhook签名
    if not verify_webhook_hmac(data, hmac_header):
        current_app.logger.warning("Webhook HMAC verification failed")
        return jsonify({'error': 'Invalid webhook signature'}), 403
    
    try:
        # 解析Webhook数据
        webhook_data = request.get_json()
        current_app.logger.info(f"Received webhook: {webhook_data}")
        
        # 根据Webhook类型处理
        webhook_type = webhook_data.get('type')
        
        if webhook_type == 'app/uninstalled':
            handle_app_uninstalled(webhook_data)
        elif webhook_type == 'orders/create':
            handle_order_created(webhook_data)
        elif webhook_type == 'orders/updated':
            handle_order_updated(webhook_data)
        elif webhook_type == 'products/create':
            handle_product_created(webhook_data)
        else:
            current_app.logger.info(f"Unhandled webhook type: {webhook_type}")
        
        return jsonify({'status': 'success'})
        
    except Exception as e:
        current_app.logger.error(f"Webhook处理失败: {str(e)}")
        return jsonify({'error': 'Webhook processing failed'}), 500

def handle_app_uninstalled(webhook_data):
    """处理应用卸载事件"""
    shop = webhook_data.get('shop')
    if shop and shop in Config.ACCESS_TOKENS:
        del Config.ACCESS_TOKENS[shop]
        current_app.logger.info(f"App uninstalled for shop: {shop}")

def handle_order_created(webhook_data):
    """处理订单创建事件"""
    order = webhook_data.get('order')
    if order:
        current_app.logger.info(f"New order created: {order.get('id')}")

def handle_order_updated(webhook_data):
    """处理订单更新事件"""
    order = webhook_data.get('order')
    if order:
        current_app.logger.info(f"Order updated: {order.get('id')}")

def handle_product_created(webhook_data):
    """处理产品创建事件"""
    product = webhook_data.get('product')
    if product:
        current_app.logger.info(f"New product created: {product.get('id')}")