You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Firebase函数中的‘SSL routines:ssl3_read_bytes:sslv3 alert handshake failure’错误?

解决Firebase函数调用Apple商家令牌API的SSL握手失败问题

核心问题分析

SSL routines:ssl3_read_bytes:sslv3 alert handshake failure 错误本质是TLS版本不匹配或缺少Apple要求的客户端证书验证——Apple支付API强制要求使用TLS 1.2及以上版本,且需通过商家身份证书完成双向SSL认证。

具体修复步骤

1. 替换废弃的请求库

request-promise已停止维护,改用对现代TLS支持更好的axios:
先安装依赖:

npm install axios

2. 配置双向SSL认证

将Apple颁发的商家身份证书(.p12或.pem格式)放到Firebase函数目录下,在请求中配置证书:

import * as functions from "firebase-functions";
import axios from "axios";
import * as fs from "fs";
import * as path from "path";
import * as https from "https";

interface ErrorResponse {
  errorMessage: string;
  httpResponseCode: number;
  statusCode: number;
}

export const unlinkMerchantToken = functions.https.onCall(async (data, context) => {
  // 替换为你的实际商家ID
  const merchantId = "YOUR_MERCHANT_ID";
  // 读取证书文件
  const certPath = path.join(__dirname, "merchant-cert.pem");
  const keyPath = path.join(__dirname, "merchant-key.pem");

  try {
    const response = await axios.post(
      `https://apple-pay-gateway.apple.com/v1/merchantId/${merchantId}/merchantToken/unlink`,
      data, // 直接传入数据,无需嵌套在data字段
      {
        headers: {
          "Content-Type": "application/json",
          "x-request-id": Math.random().toString(),
        },
        httpsAgent: new https.Agent({
          cert: fs.readFileSync(certPath),
          key: fs.readFileSync(keyPath),
          // 强制使用TLS 1.2及以上版本
          minVersion: "TLSv1.2",
        }),
      }
    );

    return response.data;
  } catch (error) {
    functions.logger.error(error);
    throw new functions.https.HttpsError(
      "unknown",
      error.response?.data?.errorMessage || "请求失败",
      error.response?.data || error
    );
  }
});

3. 修正请求格式错误

  • 原URL中的{merchantId}是占位符,必须替换为实际商家ID,不能直接保留在地址中
  • Apple API要求请求体直接传入令牌相关数据,原代码body: { data: data }的嵌套格式不符合要求

4. 确保运行环境的TLS支持

在package.json中指定Node.js 16+版本(Firebase函数默认支持,但明确指定更稳妥):

{
  "engines": {
    "node": "18"
  }
}

5. 证书格式转换(若需)

如果你的证书是.p12格式,用OpenSSL转成.pem:

# 导出证书
openssl pkcs12 -in merchant-cert.p12 -out merchant-cert.pem -clcerts -nokeys
# 导出私钥
openssl pkcs12 -in merchant-cert.p12 -out merchant-key.pem -nocerts -nodes

额外检查点

  • 确认商家ID与证书对应,且证书未过期
  • 检查Firebase函数网络权限,确保能访问apple-pay-gateway.apple.com
  • 本地调试可使用firebase emulators:start查看详细SSL日志

内容的提问来源于stack exchange,提问作者Akm127

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 14:35:35