// 测试 Alipay SDK 修复后是否能正确签名
async function test() {
  const { AlipaySdk } = await import('alipay-sdk');

  const rawKey = 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC798Z+2//v0KPswSiczFy/oGv7M99FCgQ4nh4i/F8OtWDs37+Ts/5HD0Jo4wxgrlKHLtUmsEDH2hXn2/08wj0V2cDNgUe2IrOOrpmaiVnBczjilmheUZDtnG26I38WyE3viZ7zQ5ZfNTcVxRH1gbpSC512922Vi9lFRJycIlptvKzsov11RtE29NDoKcPxTo6gMa94hLEVsDRoJroGBlGjw27Pbynwdgcjb4URacUO4T8ZFTnuYZeTyZHqyJF41WUIwRfzRSrlFUb7oRfF4LC23eXELATtpL+28Y5k4CyA6uIOPKJ02CsmCg+VjYxvV/JEw8slm/IUJiLAfjoy8vf3AgMBAAECggEAL6OyuUBE86DrivvBsUvSTfb4pygUdEj/nOHmPXO9G9s4f5CN23+I+LWTXUX+Qxqra/ugpjeRk5Vga+1Dl3ybQsh3px4W8MCGxajW4WXiS7dKOZNpTE5b7vzwinaopTuLFSTKFlmQ6Pxxw6C41oJUmKq89APt0DMrk/S5xJCoXps86xp6zbXjlPm8HtLwuL0OP0WfgnwfXm8kOkaCswS4NXrz83DcR/tUrsdNmcOUmXXuXx+hwu/x0hgMOnSZYlrea/el6deM/giU+JPbM9BMrM8IeMW0MkLSBTikSsav+hetosxuPUrCebcK4QSUrTJ+mwqWNvFFeJuM/P6HbvfTQQKBgQD8GQlwpaQBRe2VXoapjB4ShL6ml+vVNwsjhR0WiwJHavGRS/hKIe/YLRqgfpHUR0/bUOFFxpkRApBT0LevL74c1HriXzHmGhC7DLmYQD+MZmTEbHNbEgVUsJeB04Cn+teWIsKYe80YYbvpwNvsX/Eu5FutOoZCNLrR5SAR7iZNZwKBgQC+4J39gO35W1Kc91tpX5UsmuGPdO6F89BFqvydkcYAYsEi3P92lrTXiplhNnGBDe7KoM8M7gWrnjvTr9S3ZLylKK7cgKn1VUYIq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awKey + '\n-----END PRIVATE KEY-----';
  const alipayPublicKey = '-----BEGIN PUBLIC KEY-----\n' + pubKey + '\n-----END PUBLIC KEY-----';

  console.log('=== 测试1: 修复后 SDK 初始化 ===');
  const sdk = new AlipaySdk({
    appId: '2021006154659461',
    privateKey,
    keyType: 'PKCS8',
    alipayPublicKey,
    gateway: 'https://openapi.alipay.com/gateway.do',
    signType: 'RSA2',
  });
  console.log('✅ SDK 初始化成功\n');

  console.log('=== 测试2: pageExecute 生成支付表单 ===');
  try {
    const form = sdk.pageExecute('alipay.trade.wap.pay', 'POST', {
      bizContent: {
        out_trade_no: 'TEST' + Date.now(),
        total_amount: '0.01',
        subject: 'AI有声书订阅-测试',
        product_code: 'QUICK_WAP_WAY',
      },
      returnUrl: 'https://book.rrbrr.com/#/pages/payment-result/index',
      notifyUrl: 'https://book.rrbrr.com/api/payment/alipay/notify',
    });

    const actionMatch = String(form).match(/action="([^"]+)"/);
    const paymentUrl = actionMatch ? actionMatch[1] : '未能提取action';
    console.log('✅ pageExecute 调用成功');
    console.log('支付网关地址:', paymentUrl);
    console.log('表单前200字符:', String(form).substring(0, 200));
  } catch (e) {
    console.error('❌ pageExecute 失败:', e.message);
  }

  console.log('\n=== 测试3: 错误格式对比 (PKCS#1 包装) ===');
  try {
    const wrongKey = '-----BEGIN RSA PRIVATE KEY-----\n' + rawKey + '\n-----END RSA PRIVATE KEY-----';
    const sdkWrong = new AlipaySdk({
      appId: '2021006154659461',
      privateKey: wrongKey,
      keyType: 'PKCS1',
      alipayPublicKey,
      gateway: 'https://openapi.alipay.com/gateway.do',
    });
    // 能初始化但签名会是错的
    console.log('SDK 未报错（但签名会是错的，支付宝会返回 invalid-signature）');
  } catch (e) {
    console.log('SDK 报错:', e.message);
  }
}

test().catch(e => console.error('脚本异常:', e));
