from alipay import AliPay
from flask import current_app
import os

class AlipayService:
    def __init__(self):
        self.app_id = current_app.config.get('ALIPAY_APP_ID')
        self.private_key = current_app.config.get('ALIPAY_APP_PRIVATE_KEY')
        self.public_key = current_app.config.get('ALIPAY_PUBLIC_KEY')
        self.return_url = current_app.config.get('ALIPAY_RETURN_URL')
        self.notify_url = current_app.config.get('ALIPAY_NOTIFY_URL')
        self.debug = current_app.config.get('ALIPAY_DEBUG', True)

    def get_alipay_client(self):
        """获取支付宝客户端实例"""
        return AliPay(
            appid=self.app_id,
            app_notify_url=self.notify_url,
            app_private_key_string=self.private_key,
            alipay_public_key_string=self.public_key,
            sign_type="RSA2",
            debug=self.debug
        )

    def create_order_url(self, out_trade_no, total_amount, subject):
        """生成支付链接 (电脑网站支付)"""
        alipay = self.get_alipay_client()
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=out_trade_no,
            total_amount=str(total_amount),
            subject=subject,
            return_url=self.return_url,
            notify_url=self.notify_url
        )
        # 拼接支付网关 (使用最新的支付宝沙箱域名)
        gateway = "https://openapi-sandbox.dl.alipaydev.com/gateway.do" if self.debug else "https://openapi.alipay.com/gateway.do"
        return f"{gateway}?{order_string}"

    def verify_notify(self, data, signature):
        """验证通知签名"""
        alipay = self.get_alipay_client()
        return alipay.verify(data, signature)
