信封签署 (eSign)接口列表接口签署示例代码

接口签署示例代码

SignRecipient(接口签署)的完整调用示例:取 access_token → 取 JWKS 加密公钥 → 构造 JWE Credential → 调签署接口。

对应的接口文档:接口签署(SignRecipient)。

前置条件

  • 信封已发送,且包含该签署人的签署控件(如 signHere)
  • 该签署人已设置 Signing PIN,并已确认过 ERSD 授权书(首次同意须在签署页完成)
  • App 已开通 API 集成,且令牌具备 envelope:sign scope
ℹ️

Credential 不是 PIN 明文,而是 PIN 的 JWE 密文(alg=RSA-OAEP-256、enc=A256GCM,5 段 Compact)。下面六种语言都用各自的标准库或官方库手写这段加密,不依赖我方 SDK。

以下六份示例走的是同一套流程,可直接复制运行。

Go

依赖:Go 1.20+(crypto/rsa、crypto/cipher、net/http 均为标准库)

package main
 
import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"math/big"
	"net/http"
	"net/url"
	"strings"
	"time"
)
 
// 生产(新加坡)域名;测试环境用 https://api.test.sign.tencent.com
const baseURL = "https://sgapi.tencent-esign.com"
 
const (
	clientID     = "SGCL..."
	clientSecret = "..."
	spaceID      = "SGSP..." // client_credentials 模式必填
	operatorUID  = "SGUR..." // 可选:实际发件人/操作者(用于留痕)
 
	envelopeID   = "SGEV..." // quick-create 返回的 EnvelopeId
	recipientID  = "r-1"     // 建信封时 Signers[].RecipientId 填的值
	recipientUID = "SGUR..." // 该收件人在本平台的用户 ID
	signingPIN   = "666666"  // 收件人自己设置的 Signing PIN
	signatureID  = "SIG..."  // 收件人签名库里的签名 ID(默认资产)
)
 
var b64 = base64.RawURLEncoding
 
func main() {
	// ① 取 access_token(服务端对服务端;授权码模式换成你保存的 token 即可)
	var token struct {
		AccessToken string `json:"access_token"`
	}
	postForm(baseURL+"/openapi/v1/oauth/token", url.Values{
		"grant_type":    {"client_credentials"},
		"client_id":     {clientID},
		"client_secret": {clientSecret},
		"space_id":      {spaceID},
		"scope":         {"envelope:sign"},
	}, nil, &token)
 
	// ② 取 JWKS 加密公钥(use=enc 的那把)
	var jwks struct {
		Keys []struct {
			Kid string `json:"kid"`
			Use string `json:"use"`
			N   string `json:"n"`
			E   string `json:"e"`
		} `json:"keys"`
	}
	getJSON(baseURL+"/.well-known/jwks.json", &jwks)
 
	var kid string
	var publicKey rsa.PublicKey
	for _, key := range jwks.Keys {
		if key.Use != "enc" {
			continue
		}
		modulus, err := b64.DecodeString(key.N)
		if err != nil {
			panic(err)
		}
		exponent, err := b64.DecodeString(key.E)
		if err != nil {
			panic(err)
		}
		publicKey = rsa.PublicKey{
			N: new(big.Int).SetBytes(modulus),
			E: int(new(big.Int).SetBytes(exponent).Int64()),
		}
		kid = key.Kid
	}
	if kid == "" {
		panic("JWKS 中没有 use=enc 的公钥")
	}
 
	// ③ 构造 JWE Credential(RSA-OAEP-256 + A256GCM,5 段 Compact)
	issuedAt := time.Now().Unix()
	payload := fmt.Sprintf(`{"typ":"sign_pin","secret":%q,`+
		`"context":{"userId":%q,"envelopeId":%q,"recipientId":%q},`+
		`"iat":%d,"exp":%d,"jti":%q}`,
		signingPIN, recipientUID, envelopeID, recipientID,
		issuedAt, issuedAt+60, randomID())
	credential := buildCredential(&publicKey, kid, []byte(payload))
 
	// ④ 调签署接口。幂等键必填:同一笔业务重试请复用同一个值
	path := fmt.Sprintf("/openapi/v1/envelopes/%s/recipients/%s/sign", envelopeID, recipientID)
	var result map[string]any
	postJSON(baseURL+path, map[string]string{
		"Credential":  credential,
		"SignatureId": signatureID,
	}, map[string]string{
		"Authorization":      "Bearer " + token.AccessToken,
		"X-Operator-User-Id": operatorUID,
		"Idempotency-Key":    "order-20240924-001-r1",
	}, &result)
 
	pretty, _ := json.MarshalIndent(result, "", "  ")
	fmt.Println(string(pretty))
}
 
// 把 PIN 加密成 SignRecipient 要求的 Credential
// 凭据只活 60 秒、jti 一次性:每次调用(含失败重试)都必须重新生成一份
func buildCredential(publicKey *rsa.PublicKey, kid string, payload []byte) string {
	header, _ := json.Marshal(map[string]string{
		"alg": "RSA-OAEP-256", "enc": "A256GCM", "kid": kid, "typ": "JWE",
	})
	// protected header 的原文就是后面的 AAD,必须原样参与加密
	protectedHeader := b64.EncodeToString(header)
 
	// 随机生成 32 字节 CEK,用服务端 RSA 公钥包封
	// MGF1 摘要必须与 OAEP 的 hash 一致,这里取 SHA-256
	cek := make([]byte, 32)
	if _, err := rand.Read(cek); err != nil {
		panic(err)
	}
	encryptedKey, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, cek, nil)
	if err != nil {
		panic(err)
	}
 
	// AES-256-GCM:AAD = protected header
	iv := make([]byte, 12)
	if _, err := rand.Read(iv); err != nil {
		panic(err)
	}
	block, err := aes.NewCipher(cek)
	if err != nil {
		panic(err)
	}
	gcm, err := cipher.NewGCM(block)
	if err != nil {
		panic(err)
	}
	sealed := gcm.Seal(nil, iv, payload, []byte(protectedHeader))
 
	// JWE Compact 5 段:protected.encryptedKey.iv.ciphertext.tag
	// 加密输出是 ciphertext || tag,末尾 16 字节要单独成段
	return strings.Join([]string{
		protectedHeader,
		b64.EncodeToString(encryptedKey),
		b64.EncodeToString(iv),
		b64.EncodeToString(sealed[:len(sealed)-16]),
		b64.EncodeToString(sealed[len(sealed)-16:]),
	}, ".")
}
 
func randomID() string {
	buf := make([]byte, 16)
	if _, err := rand.Read(buf); err != nil {
		panic(err)
	}
	return hex.EncodeToString(buf)
}
 
func postForm(endpoint string, form url.Values, headers map[string]string, out any) {
	request, err := http.NewRequest(http.MethodPost, endpoint, strings.NewReader(form.Encode()))
	if err != nil {
		panic(err)
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	send(request, headers, out)
}
 
func postJSON(endpoint string, body any, headers map[string]string, out any) {
	encoded, err := json.Marshal(body)
	if err != nil {
		panic(err)
	}
	request, err := http.NewRequest(http.MethodPost, endpoint, bytes.NewReader(encoded))
	if err != nil {
		panic(err)
	}
	request.Header.Set("Content-Type", "application/json")
	send(request, headers, out)
}
 
func getJSON(endpoint string, out any) {
	request, err := http.NewRequest(http.MethodGet, endpoint, nil)
	if err != nil {
		panic(err)
	}
	send(request, nil, out)
}
 
func send(request *http.Request, headers map[string]string, out any) {
	for name, value := range headers {
		request.Header.Set(name, value)
	}
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	body, err := io.ReadAll(response.Body)
	if err != nil {
		panic(err)
	}
	if response.StatusCode != http.StatusOK {
		panic(fmt.Sprintf("HTTP %d: %s", response.StatusCode, body))
	}
	if err := json.Unmarshal(body, out); err != nil {
		panic(fmt.Sprintf("解析响应失败: %v (%s)", err, body))
	}
}

Python

依赖:Python 3.8+、cryptography(pip install cryptography)

"""Tencent eSign Global —— 接口签署(SignRecipient)示例。"""
 
import base64
import json
import os
import time
import urllib.parse
import urllib.request
import uuid
 
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding, rsa
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
 
# 生产(新加坡)域名;测试环境用 https://api.test.sign.tencent.com
BASE_URL = "https://sgapi.tencent-esign.com"
 
CLIENT_ID = "SGCL..."
CLIENT_SECRET = "..."
SPACE_ID = "SGSP..."  # client_credentials 模式必填
OPERATOR_USER_ID = "SGUR..."  # 可选:实际发件人/操作者(用于留痕)
 
ENVELOPE_ID = "SGEV..."  # quick-create 返回的 EnvelopeId
RECIPIENT_ID = "r-1"  # 建信封时 Signers[].RecipientId 填的值
RECIPIENT_USER_ID = "SGUR..."  # 该收件人在本平台的用户 ID
SIGNING_PIN = "666666"  # 收件人自己设置的 Signing PIN
SIGNATURE_ID = "SIG..."  # 收件人签名库里的签名 ID(默认资产)
 
 
def b64u(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
 
 
def fetch_access_token() -> str:
    """① 取 access_token(服务端对服务端;授权码模式换成你保存的 token 即可)"""
    form = urllib.parse.urlencode({
        "grant_type": "client_credentials",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "space_id": SPACE_ID,
        "scope": "envelope:sign",
    }).encode()
    return post(
        f"{BASE_URL}/openapi/v1/oauth/token", form, content_type="application/x-www-form-urlencoded"
    )["access_token"]
 
 
def fetch_encryption_key():
    """② 取 JWKS 加密公钥(use=enc 的那把)"""
    jwks = get(f"{BASE_URL}/.well-known/jwks.json")
    for jwk in jwks["keys"]:
        if jwk.get("use") != "enc":
            continue
        numbers = rsa.RSAPublicNumbers(
            e=int.from_bytes(base64.urlsafe_b64decode(jwk["e"] + "=="), "big"),
            n=int.from_bytes(base64.urlsafe_b64decode(jwk["n"] + "=="), "big"),
        )
        return jwk["kid"], numbers.public_key()
    raise RuntimeError("JWKS 中没有 use=enc 的公钥")
 
 
def build_credential(public_key, kid: str) -> str:
    """③ 构造 JWE Credential(RSA-OAEP-256 + A256GCM,5 段 Compact)。
 
    凭据只活 60 秒、jti 一次性:每次调用(含失败重试)都必须重新生成一份
    """
    header = json.dumps(
        {"alg": "RSA-OAEP-256", "enc": "A256GCM", "kid": kid, "typ": "JWE"},
        separators=(",", ":"),
    ).encode()
    # protected header 的原文就是后面的 AAD,必须原样参与加密
    protected_header = b64u(header)
 
    issued_at = int(time.time())
    payload = json.dumps(
        {
            "typ": "sign_pin",
            "secret": SIGNING_PIN,
            "context": {
                "userId": RECIPIENT_USER_ID,
                "envelopeId": ENVELOPE_ID,
                "recipientId": RECIPIENT_ID,
            },
            "iat": issued_at,
            "exp": issued_at + 60,
            "jti": str(uuid.uuid4()),
        },
        separators=(",", ":"),
    ).encode()
 
    # 随机生成 32 字节 CEK,用服务端 RSA 公钥包封
    # MGF1 摘要必须与 OAEP 的 hash 一致,这里取 SHA-256
    cek = os.urandom(32)
    encrypted_key = public_key.encrypt(
        cek,
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None),
    )
 
    # AES-256-GCM:AAD = protected header
    iv = os.urandom(12)
    sealed = AESGCM(cek).encrypt(iv, payload, protected_header.encode())
 
    # 加密输出是 ciphertext || tag,末尾 16 字节要单独成段
    # JWE Compact 5 段:protected.encryptedKey.iv.ciphertext.tag
    return ".".join([
        protected_header,
        b64u(encrypted_key),
        b64u(iv),
        b64u(sealed[:-16]),
        b64u(sealed[-16:]),
    ])
 
 
def sign(access_token: str, credential: str) -> dict:
    """④ 调签署接口。幂等键必填:同一笔业务重试请复用同一个值"""
    url = f"{BASE_URL}/openapi/v1/envelopes/{ENVELOPE_ID}/recipients/{RECIPIENT_ID}/sign"
    body = json.dumps({"Credential": credential, "SignatureId": SIGNATURE_ID}).encode()
    return post(
        url,
        body,
        headers={
            "Authorization": f"Bearer {access_token}",
            "X-Operator-User-Id": OPERATOR_USER_ID,
            "Idempotency-Key": "order-20240924-001-r1",
        },
    )
 
 
def get(url: str) -> dict:
    with urllib.request.urlopen(urllib.request.Request(url, method="GET"), timeout=30) as response:
        return json.loads(response.read().decode())
 
 
def post(url: str, body: bytes, headers: dict = None, content_type: str = "application/json") -> dict:
    request = urllib.request.Request(
        url,
        data=body,
        headers={"Content-Type": content_type, **(headers or {})},
        method="POST",
    )
    with urllib.request.urlopen(request, timeout=30) as response:
        return json.loads(response.read().decode())
 
 
def main() -> None:
    access_token = fetch_access_token()
    kid, public_key = fetch_encryption_key()
    credential = build_credential(public_key, kid)
    print(json.dumps(sign(access_token, credential), indent=2, ensure_ascii=False))
 
 
if __name__ == "__main__":
    main()

Java

依赖:JDK 11+、jackson-databind(仅用于 JSON 解析)

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
 
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.spec.PSource;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.SecureRandom;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.UUID;
 
/**
 * Tencent eSign Global —— 接口签署(SignRecipient)最小可运行示例。
 *
 * 依赖:JDK 11+、jackson-databind(仅用于 JSON;见文末依赖坐标)。
 *
 * 流程:① 取 access_token → ② 取 JWKS 加密公钥 → ③ 本地构造 JWE Credential → ④ 调签署接口。
 *
 * 说明:Credential 用 JDK 原生 API 手工组装 JWE Compact,不依赖任何 JOSE 库。
 * 各家 JOSE 库对 RSA-OAEP-256 的 MGF1 摘要默认值不一致(有的默认 SHA-1),会导致
 * 服务端解密失败(统一返回 AUTH.CREDENTIAL_INVALID),因此这里显式指定 SHA-256。
 */
public class SignRecipientExample {
 
    // ===== 按你的环境填写 =====
    // 生产(新加坡)域名;测试环境用 https://api.test.sign.tencent.com
    private static final String BASE_URL = "https://sgapi.tencent-esign.com";
    private static final String CLIENT_ID = "SGCL...";
    private static final String CLIENT_SECRET = "...";
    private static final String SPACE_ID = "SGSP..."; // client_credentials 模式必填
    private static final String OPERATOR_USER_ID = "SGUR..."; // 可选:实际发件人/操作者(用于留痕)
 
    private static final String ENVELOPE_ID = "SGEV..."; // quick-create 返回的 EnvelopeId
    private static final String RECIPIENT_ID = "r-1"; // 建信封时 Signers[].RecipientId 填的值
    private static final String RECIPIENT_USER_ID = "SGUR..."; // 该收件人在本平台的用户 ID
    private static final String SIGNING_PIN = "666666"; // 收件人自己设置的 Signing PIN
    private static final String SIGNATURE_ID = "SIG..."; // 收件人签名库里的签名 ID(默认资产)
 
    private static final ObjectMapper JSON = new ObjectMapper();
    private static final Base64.Encoder B64 = Base64.getUrlEncoder().withoutPadding();
    private static final Base64.Decoder B64D = Base64.getUrlDecoder();
    private static final SecureRandom RANDOM = new SecureRandom();
 
    public static void main(String[] args) throws Exception {
        HttpClient http = HttpClient.newHttpClient();
 
        // ① 取 access_token(服务端对服务端;授权码模式换成你保存的 token 即可)
        String form = "grant_type=client_credentials"
                + "&client_id=" + enc(CLIENT_ID)
                + "&client_secret=" + enc(CLIENT_SECRET)
                + "&space_id=" + enc(SPACE_ID)
                + "&scope=" + enc("envelope:sign");
        HttpRequest tokenRequest = HttpRequest.newBuilder(URI.create(BASE_URL + "/openapi/v1/oauth/token"))
                .header("Content-Type", "application/x-www-form-urlencoded")
                .POST(HttpRequest.BodyPublishers.ofString(form, StandardCharsets.UTF_8))
                .build();
        String accessToken = JSON.readTree(send(http, tokenRequest).body()).path("access_token").asText();
 
        // ② 取 JWKS 加密公钥(use=enc 的那把)
        HttpRequest jwksRequest = HttpRequest.newBuilder(URI.create(BASE_URL + "/.well-known/jwks.json")).GET().build();
        JsonNode jwk = null;
        for (JsonNode key : JSON.readTree(send(http, jwksRequest).body()).path("keys")) {
            if ("enc".equals(key.path("use").asText())) {
                jwk = key;
                break;
            }
        }
        if (jwk == null) {
            throw new IllegalStateException("JWKS 中没有 use=enc 的公钥");
        }
        RSAPublicKey publicKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(
                new RSAPublicKeySpec(
                        new BigInteger(1, B64D.decode(jwk.path("n").asText())),
                        new BigInteger(1, B64D.decode(jwk.path("e").asText()))));
 
        // ③ 构造 JWE Credential(RSA-OAEP-256 + A256GCM,5 段 Compact)
        String credential = buildCredential(publicKey, jwk.path("kid").asText(),
                SIGNING_PIN, RECIPIENT_USER_ID, ENVELOPE_ID, RECIPIENT_ID);
 
        // ④ 调签署接口。幂等键必填:同一笔业务重试请复用同一个值
        ObjectNode body = JSON.createObjectNode();
        body.put("Credential", credential);
        body.put("SignatureId", SIGNATURE_ID);
        HttpRequest signRequest = HttpRequest.newBuilder(URI.create(BASE_URL
                        + "/openapi/v1/envelopes/" + ENVELOPE_ID
                        + "/recipients/" + RECIPIENT_ID + "/sign"))
                .header("Authorization", "Bearer " + accessToken)
                .header("X-Operator-User-Id", OPERATOR_USER_ID)
                .header("Idempotency-Key", "order-20240924-001-r1")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(body.toString(), StandardCharsets.UTF_8))
                .build();
        String responseBody = send(http, signRequest).body();
        System.out.println(responseBody);
 
        JsonNode response = JSON.readTree(responseBody).path("Response");
        JsonNode error = response.path("Error");
        if (!error.isMissingNode() && !error.isNull()) {
            System.err.println("签署失败 " + error.path("Code").asText() + ": " + error.path("Message").asText());
            return;
        }
        JsonNode data = response.path("Data");
        System.out.println("RecipientStatus=" + data.path("RecipientStatus").asText()
                + " EnvelopeCompleted=" + data.path("EnvelopeCompleted").asBoolean()
                + " SignedAt=" + data.path("SignedAt").asText()
                + " IdempotentReplay=" + data.path("IdempotentReplay").asBoolean());
    }
 
    /**
     * 把 PIN 加密成 SignRecipient 要求的 Credential
     *
     * <p>凭据只活 60 秒、jti 一次性:每次调用(含失败重试)都必须重新生成一份
     * context 三个值必须与路径参数和收件人完全一致,任一不符都会被判为凭据无效</p>
     */
    private static String buildCredential(RSAPublicKey publicKey, String kid, String pin,
                                          String userId, String envelopeId, String recipientId) throws Exception {
        // protected header 的原文就是后面的 AAD,必须原样参与加密
        String headerJson = "{\"alg\":\"RSA-OAEP-256\",\"enc\":\"A256GCM\",\"kid\":\"" + kid + "\",\"typ\":\"JWE\"}";
        String protectedHeader = B64.encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
 
        // 随机生成 32 字节 CEK,用服务端 RSA 公钥包封
        // MGF1 摘要必须与 OAEP 的 hash 一致,这里取 SHA-256
        byte[] cek = new byte[32];
        RANDOM.nextBytes(cek);
        Cipher rsa = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        rsa.init(Cipher.ENCRYPT_MODE, publicKey,
                new OAEPParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, PSource.PSpecified.DEFAULT));
        byte[] encryptedKey = rsa.doFinal(cek);
 
        // 明文载荷
        long iat = System.currentTimeMillis() / 1000L;
        String payloadJson = "{\"typ\":\"sign_pin\",\"secret\":\"" + pin + "\","
                + "\"context\":{\"userId\":\"" + userId + "\","
                + "\"envelopeId\":\"" + envelopeId + "\","
                + "\"recipientId\":\"" + recipientId + "\"},"
                + "\"iat\":" + iat + ",\"exp\":" + (iat + 60) + ","
                + "\"jti\":\"" + UUID.randomUUID() + "\"}";
 
        // AES-256-GCM:AAD = protected header
        byte[] iv = new byte[12];
        RANDOM.nextBytes(iv);
        Cipher gcm = Cipher.getInstance("AES/GCM/NoPadding");
        gcm.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(cek, "AES"), new GCMParameterSpec(128, iv));
        gcm.updateAAD(protectedHeader.getBytes(StandardCharsets.UTF_8));
        byte[] sealed = gcm.doFinal(payloadJson.getBytes(StandardCharsets.UTF_8));
        // 加密输出是 ciphertext || tag,末尾 16 字节要单独成段
        byte[] ciphertext = Arrays.copyOfRange(sealed, 0, sealed.length - 16);
        byte[] tag = Arrays.copyOfRange(sealed, sealed.length - 16, sealed.length);
 
        return protectedHeader
                + "." + B64.encodeToString(encryptedKey)
                + "." + B64.encodeToString(iv)
                + "." + B64.encodeToString(ciphertext)
                + "." + B64.encodeToString(tag);
    }
 
    private static HttpResponse<String> send(HttpClient http, HttpRequest request) throws Exception {
        HttpResponse<String> response =
                http.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
        if (response.statusCode() != 200) {
            throw new IllegalStateException("HTTP " + response.statusCode() + ": " + response.body());
        }
        return response;
    }
 
    private static String enc(String value) {
        return URLEncoder.encode(value, StandardCharsets.UTF_8);
    }
}

Node.js

依赖:Node.js 18+(内置 fetch 与 node:crypto)

import crypto from 'node:crypto';
 
// 生产(新加坡)域名;测试环境用 https://api.test.sign.tencent.com
const BASE_URL = 'https://sgapi.tencent-esign.com';
 
const CLIENT_ID = 'SGCL...';
const CLIENT_SECRET = '...';
const SPACE_ID = 'SGSP...'; // client_credentials 模式必填
const OPERATOR_USER_ID = 'SGUR...'; // 可选:实际发件人/操作者(用于留痕)
 
const ENVELOPE_ID = 'SGEV...'; // quick-create 返回的 EnvelopeId
const RECIPIENT_ID = 'r-1'; // 建信封时 Signers[].RecipientId 填的值
const RECIPIENT_USER_ID = 'SGUR...'; // 该收件人在本平台的用户 ID
const SIGNING_PIN = '666666'; // 收件人自己设置的 Signing PIN
const SIGNATURE_ID = 'SIG...'; // 收件人签名库里的签名 ID(默认资产)
 
const b64 = (buffer) => Buffer.from(buffer).toString('base64url');
 
// ① 取 access_token(服务端对服务端;授权码模式换成你保存的 token 即可)
async function fetchAccessToken() {
  const body = new URLSearchParams({
    grant_type: 'client_credentials',
    client_id: CLIENT_ID,
    client_secret: CLIENT_SECRET,
    space_id: SPACE_ID,
    scope: 'envelope:sign',
  });
  const response = await fetch(`${BASE_URL}/openapi/v1/oauth/token`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body,
  });
  return (await readJson(response)).access_token;
}
 
// ② 取 JWKS 加密公钥(use=enc 的那把)
async function fetchEncryptionKey() {
  const jwks = await readJson(await fetch(`${BASE_URL}/.well-known/jwks.json`));
  const jwk = jwks.keys.find((key) => key.use === 'enc');
  if (!jwk) throw new Error('JWKS 中没有 use=enc 的公钥');
  return { kid: jwk.kid, publicKey: crypto.createPublicKey({ key: jwk, format: 'jwk' }) };
}
 
// ③ 构造 JWE Credential(RSA-OAEP-256 + A256GCM,5 段 Compact)
// 凭据只活 60 秒、jti 一次性:每次调用(含失败重试)都必须重新生成一份
function buildCredential(publicKey, kid) {
  const header = JSON.stringify({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid, typ: 'JWE' });
  // protected header 的原文就是后面的 AAD,必须原样参与加密
  const protectedHeader = b64(header);
  const issuedAt = Math.floor(Date.now() / 1000);
  const payload = JSON.stringify({
    typ: 'sign_pin',
    secret: SIGNING_PIN,
    context: { userId: RECIPIENT_USER_ID, envelopeId: ENVELOPE_ID, recipientId: RECIPIENT_ID },
    iat: issuedAt,
    exp: issuedAt + 60,
    jti: crypto.randomUUID(),
  });
 
  // 随机生成 32 字节 CEK,用服务端 RSA 公钥包封
  // MGF1 摘要必须与 OAEP 的 hash 一致,这里取 SHA-256
  const cek = crypto.randomBytes(32);
  const encryptedKey = crypto.publicEncrypt(
    { key: publicKey, padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
    cek,
  );
 
  // AES-256-GCM:AAD = protected header
  const iv = crypto.randomBytes(12);
  const cipher = crypto.createCipheriv('aes-256-gcm', cek, iv);
  cipher.setAAD(Buffer.from(protectedHeader, 'utf8'));
  const ciphertext = Buffer.concat([cipher.update(payload, 'utf8'), cipher.final()]);
  const tag = cipher.getAuthTag();
 
  return [protectedHeader, b64(encryptedKey), b64(iv), b64(ciphertext), b64(tag)].join('.');
}
 
// ④ 调签署接口。幂等键必填:同一笔业务重试请复用同一个值
async function main() {
  const accessToken = await fetchAccessToken();
  const { kid, publicKey } = await fetchEncryptionKey();
  const credential = buildCredential(publicKey, kid);
 
  const url = `${BASE_URL}/openapi/v1/envelopes/${ENVELOPE_ID}/recipients/${RECIPIENT_ID}/sign`;
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${accessToken}`,
      'X-Operator-User-Id': OPERATOR_USER_ID,
      'Idempotency-Key': 'order-20240924-001-r1',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ Credential: credential, SignatureId: SIGNATURE_ID }),
  });
  console.log(JSON.stringify(await readJson(response), null, 2));
}
 
async function readJson(response) {
  const text = await response.text();
  if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);
  return JSON.parse(text);
}
 
main().catch((error) => {
  console.error(error);
  process.exit(1);
});

C# (.NET)

依赖:.NET 8+(System.Security.Cryptography 内置)

using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
 
// 生产(新加坡)域名;测试环境用 https://api.test.sign.tencent.com
const string BaseUrl = "https://sgapi.tencent-esign.com";
 
const string ClientId = "SGCL...";
const string ClientSecret = "...";
const string SpaceId = "SGSP..."; // client_credentials 模式必填
const string OperatorUserId = "SGUR..."; // 可选:实际发件人/操作者(用于留痕)
 
const string EnvelopeId = "SGEV..."; // quick-create 返回的 EnvelopeId
const string RecipientId = "r-1"; // 建信封时 Signers[].RecipientId 填的值
const string RecipientUserId = "SGUR..."; // 该收件人在本平台的用户 ID
const string SigningPin = "666666"; // 收件人自己设置的 Signing PIN
const string SignatureId = "SIG..."; // 收件人签名库里的签名 ID(默认资产)
 
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
 
// ① 取 access_token(服务端对服务端;授权码模式换成你保存的 token 即可)
var token = await PostAsync(http, $"{BaseUrl}/openapi/v1/oauth/token", new FormUrlEncodedContent(
    new Dictionary<string, string>
    {
        ["grant_type"] = "client_credentials",
        ["client_id"] = ClientId,
        ["client_secret"] = ClientSecret,
        ["space_id"] = SpaceId,
        ["scope"] = "envelope:sign",
    }));
 
// ② 取 JWKS 加密公钥(use=enc 的那把)
var jwks = await GetAsync(http, $"{BaseUrl}/.well-known/jwks.json");
JsonNode? encryptionKey = null;
foreach (var key in jwks["keys"]!.AsArray())
{
    if (key!["use"]?.GetValue<string>() == "enc")
    {
        encryptionKey = key;
        break;
    }
}
if (encryptionKey is null)
{
    throw new InvalidOperationException("JWKS 中没有 use=enc 的公钥");
}
 
using var rsa = RSA.Create();
rsa.ImportParameters(new RSAParameters
{
    Modulus = Base64UrlDecode(encryptionKey["n"]!.GetValue<string>()),
    Exponent = Base64UrlDecode(encryptionKey["e"]!.GetValue<string>()),
});
 
// ③ 构造 JWE Credential(RSA-OAEP-256 + A256GCM,5 段 Compact)
var issuedAt = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
var payload = new JsonObject
{
    ["typ"] = "sign_pin",
    ["secret"] = SigningPin,
    ["context"] = new JsonObject
    {
        ["userId"] = RecipientUserId,
        ["envelopeId"] = EnvelopeId,
        ["recipientId"] = RecipientId,
    },
    ["iat"] = issuedAt,
    ["exp"] = issuedAt + 60,
    ["jti"] = Guid.NewGuid().ToString(),
}.ToJsonString();
var credential = BuildCredential(rsa, encryptionKey["kid"]!.GetValue<string>(), payload);
 
// ④ 调签署接口。幂等键必填:同一笔业务重试请复用同一个值
var signRequest = new HttpRequestMessage(
    HttpMethod.Post,
    $"{BaseUrl}/openapi/v1/envelopes/{EnvelopeId}/recipients/{RecipientId}/sign")
{
    Content = new StringContent(
        new JsonObject { ["Credential"] = credential, ["SignatureId"] = SignatureId }.ToJsonString(),
        Encoding.UTF8,
        "application/json"),
};
signRequest.Headers.Add("Authorization", $"Bearer {token["access_token"]!.GetValue<string>()}");
signRequest.Headers.Add("X-Operator-User-Id", OperatorUserId);
signRequest.Headers.Add("Idempotency-Key", "order-20240924-001-r1");
 
var signResponse = await http.SendAsync(signRequest);
var signBody = await signResponse.Content.ReadAsStringAsync();
if (!signResponse.IsSuccessStatusCode)
{
    throw new InvalidOperationException($"HTTP {(int)signResponse.StatusCode}: {signBody}");
}
Console.WriteLine(signBody);
 
// 把 PIN 加密成 SignRecipient 要求的 Credential
// 凭据只活 60 秒、jti 一次性:每次调用(含失败重试)都必须重新生成一份
static string BuildCredential(RSA rsa, string kid, string payload)
{
    var header = new JsonObject
    {
        ["alg"] = "RSA-OAEP-256",
        ["enc"] = "A256GCM",
        ["kid"] = kid,
        ["typ"] = "JWE",
    }.ToJsonString();
    // protected header 的原文就是后面的 AAD,必须原样参与加密
    var protectedHeader = Base64UrlEncode(Encoding.UTF8.GetBytes(header));
 
    // 随机生成 32 字节 CEK,用服务端 RSA 公钥包封
    // MGF1 摘要必须与 OAEP 的 hash 一致,这里取 SHA-256
    var cek = RandomNumberGenerator.GetBytes(32);
    var encryptedKey = rsa.Encrypt(cek, RSAEncryptionPadding.OaepSHA256);
 
    // AES-256-GCM:AAD = protected header
    var iv = RandomNumberGenerator.GetBytes(12);
    var plaintext = Encoding.UTF8.GetBytes(payload);
    var ciphertext = new byte[plaintext.Length];
    var tag = new byte[16];
    using var aes = new AesGcm(cek, 16);
    aes.Encrypt(iv, plaintext, ciphertext, tag, Encoding.UTF8.GetBytes(protectedHeader));
 
    // 加密输出是 ciphertext || tag,末尾 16 字节要单独成段
    // JWE Compact 5 段:protected.encryptedKey.iv.ciphertext.tag
    return string.Join(
        '.',
        protectedHeader,
        Base64UrlEncode(encryptedKey),
        Base64UrlEncode(iv),
        Base64UrlEncode(ciphertext),
        Base64UrlEncode(tag));
}
 
static string Base64UrlEncode(byte[] value) =>
    Convert.ToBase64String(value).TrimEnd('=').Replace('+', '-').Replace('/', '_');
 
static byte[] Base64UrlDecode(string value)
{
    var padded = value.Replace('-', '+').Replace('_', '/');
    return Convert.FromBase64String(padded.PadRight((padded.Length + 3) / 4 * 4, '='));
}
 
static async Task<JsonNode> PostAsync(HttpClient http, string url, HttpContent content)
{
    var response = await http.PostAsync(url, content);
    var body = await response.Content.ReadAsStringAsync();
    if (!response.IsSuccessStatusCode)
    {
        throw new InvalidOperationException($"HTTP {(int)response.StatusCode}: {body}");
    }
    return JsonNode.Parse(body)!;
}
 
static async Task<JsonNode> GetAsync(HttpClient http, string url)
{
    var response = await http.GetAsync(url);
    var body = await response.Content.ReadAsStringAsync();
    if (!response.IsSuccessStatusCode)
    {
        throw new InvalidOperationException($"HTTP {(int)response.StatusCode}: {body}");
    }
    return JsonNode.Parse(body)!;
}

PHP

依赖:PHP 7.4+、phpseclib 3(composer require phpseclib/phpseclib:~3.0)——openssl 扩展设不了 OAEP 的 MGF1,RSA 部分必须走 phpseclib

<?php
 
/**
 * Tencent eSign Global —— 接口签署(SignRecipient)示例。
 *
 * 依赖:PHP 7.4+、openssl 扩展、phpseclib 3(composer require phpseclib/phpseclib:~3.0)
 */
 
require __DIR__ . '/vendor/autoload.php';
 
use phpseclib3\Crypt\RSA;
 
// 生产(新加坡)域名;测试环境用 https://api.test.sign.tencent.com
const BASE_URL = 'https://sgapi.tencent-esign.com';
 
const CLIENT_ID = 'SGCL...';
const CLIENT_SECRET = '...';
const SPACE_ID = 'SGSP...'; // client_credentials 模式必填
const OPERATOR_USER_ID = 'SGUR...'; // 可选:实际发件人/操作者(用于留痕)
 
const ENVELOPE_ID = 'SGEV...'; // quick-create 返回的 EnvelopeId
const RECIPIENT_ID = 'r-1'; // 建信封时 Signers[].RecipientId 填的值
const RECIPIENT_USER_ID = 'SGUR...'; // 该收件人在本平台的用户 ID
const SIGNING_PIN = '666666'; // 收件人自己设置的 Signing PIN
const SIGNATURE_ID = 'SIG...'; // 收件人签名库里的签名 ID(默认资产)
 
// ① 取 access_token(服务端对服务端;授权码模式换成你保存的 token 即可)
$token = post(BASE_URL . '/openapi/v1/oauth/token', http_build_query([
    'grant_type' => 'client_credentials',
    'client_id' => CLIENT_ID,
    'client_secret' => CLIENT_SECRET,
    'space_id' => SPACE_ID,
    'scope' => 'envelope:sign',
]), 'application/x-www-form-urlencoded');
 
// ② 取 JWKS 加密公钥(use=enc 的那把)
$jwks = get(BASE_URL . '/.well-known/jwks.json');
$jwk = null;
foreach ($jwks['keys'] as $candidate) {
    if (($candidate['use'] ?? '') === 'enc') {
        $jwk = $candidate;
        break;
    }
}
if ($jwk === null) {
    throw new RuntimeException('JWKS 中没有 use=enc 的公钥');
}
 
// ③ 构造 JWE Credential(RSA-OAEP-256 + A256GCM,5 段 Compact)
$credential = build_credential($jwk);
 
// ④ 调签署接口。幂等键必填:同一笔业务重试请复用同一个值
$result = post(
    BASE_URL . '/openapi/v1/envelopes/' . ENVELOPE_ID . '/recipients/' . RECIPIENT_ID . '/sign',
    json_encode(['Credential' => $credential, 'SignatureId' => SIGNATURE_ID], JSON_UNESCAPED_SLASHES),
    'application/json',
    [
        'Authorization: Bearer ' . $token['access_token'],
        'X-Operator-User-Id: ' . OPERATOR_USER_ID,
        'Idempotency-Key: order-20240924-001-r1',
    ]
);
echo json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
 
// 把 PIN 加密成 SignRecipient 要求的 Credential
// 凭据只活 60 秒、jti 一次性:每次调用(含失败重试)都必须重新生成一份
function build_credential(array $jwk): string
{
    $header = json_encode([
        'alg' => 'RSA-OAEP-256',
        'enc' => 'A256GCM',
        'kid' => $jwk['kid'],
        'typ' => 'JWE',
    ], JSON_UNESCAPED_SLASHES);
    // protected header 的原文就是后面的 AAD,必须原样参与加密
    $protectedHeader = base64url_encode($header);
 
    $issuedAt = time();
    $payload = json_encode([
        'typ' => 'sign_pin',
        'secret' => SIGNING_PIN,
        'context' => [
            'userId' => RECIPIENT_USER_ID,
            'envelopeId' => ENVELOPE_ID,
            'recipientId' => RECIPIENT_ID,
        ],
        'iat' => $issuedAt,
        'exp' => $issuedAt + 60,
        'jti' => bin2hex(random_bytes(16)),
    ], JSON_UNESCAPED_SLASHES);
 
    // 随机生成 32 字节 CEK,用服务端 RSA 公钥包封
    // MGF1 摘要必须与 OAEP 的 hash 一致,这里取 SHA-256
    $cek = random_bytes(32);
    $rsa = RSA::loadFormat('JWK', json_encode($jwk))
        ->withHash('sha256')
        ->withMGFHash('sha256')
        ->withPadding(RSA::ENCRYPTION_OAEP);
    $encryptedKey = $rsa->encrypt($cek);
 
    // AES-256-GCM:AAD = protected header
    $iv = random_bytes(12);
    $tag = '';
    $ciphertext = openssl_encrypt($payload, 'aes-256-gcm', $cek, OPENSSL_RAW_DATA, $iv, $tag, $protectedHeader);
    if ($ciphertext === false) {
        throw new RuntimeException('AES-GCM 加密失败:' . openssl_error_string());
    }
 
    // 加密输出是 ciphertext || tag,末尾 16 字节要单独成段
    // JWE Compact 5 段:protected.encryptedKey.iv.ciphertext.tag
    return implode('.', [
        $protectedHeader,
        base64url_encode($encryptedKey),
        base64url_encode($iv),
        base64url_encode($ciphertext),
        base64url_encode($tag),
    ]);
}
 
function base64url_encode(string $raw): string
{
    return rtrim(strtr(base64_encode($raw), '+/', '-_'), '=');
}
 
function get(string $url): array
{
    $context = stream_context_create(['http' => ['method' => 'GET', 'timeout' => 30, 'ignore_errors' => true]]);
    $body = @file_get_contents($url, false, $context);
    if ($body === false) {
        throw new RuntimeException("GET {$url} 失败");
    }
    return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}
 
function post(string $url, string $payload, string $contentType, array $headers = []): array
{
    $context = stream_context_create(['http' => [
        'method' => 'POST',
        'header' => implode("\r\n", array_merge(["Content-Type: {$contentType}"], $headers)),
        'content' => $payload,
        'timeout' => 30,
        'ignore_errors' => true,
    ]]);
    $body = @file_get_contents($url, false, $context);
    if ($body === false) {
        throw new RuntimeException("POST {$url} 失败");
    }
    return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}

四条容易踩的规则

  • Credential 只活 60 秒、jti 一次性:每次调用(含失败重试)都要重新加密生成一份
  • context 的 userId / envelopeId / recipientId 必须与本次签署人、URL 完全一致,任一不符都会泛化为 AUTH.CREDENTIAL_INVALID
  • RSA-OAEP-256 的 MGF1 摘要必须是 SHA-256:部分 JOSE 库默认用 SHA-1,会直接解密失败,请显式指定
  • 幂等键必填:同一笔业务重试复用同一个 Idempotency-Key,命中此前成功请求时原样返回(IdempotentReplay=true),不会重复签署

报错对照

先做一次自检,确认公钥能取到:

curl -s https://sgapi.tencent-esign.com/.well-known/jwks.json | jq .

应返回带 use=enc、kid、alg=RSA-OAEP-256 的 RSA 公钥;404 说明网关未放行 /.well-known/*,请联系我们。

报错先查这几项
AUTH.CREDENTIAL_REQUIRED请求体没带 Credential(明文 PIN 默认不接受,需我们为该 App 开通豁免)
AUTH.CREDENTIAL_INVALIDjti 复用了;context 三项与签署人/URL 不一致;alg/enc/kid 不符;MGF1 不是 SHA-256;凭据不是 5 段
AUTH.CREDENTIAL_EXPIRED从加密到调用超过 60 秒,或客户端时钟偏差超过 30 秒
AUTH.PIN_NOT_CONFIGURED该签署人尚未设置 Signing PIN
SIGNING.CONSENT_REQUIRED该签署人尚未同意 ERSD 授权书
SIGNING.SIGNATURE_REQUIRED信封里没有签署控件,或该签署人名下没有可用的签名资产
INVALID_REQUEST缺幂等键(Idempotency-Key 头或 body IdempotencyKey 二选一)
RECIPIENT.NOT_RECIPIENT路径里的 recipientId 不是该信封的签署人
ENVELOPE.INVALID_STATUS信封已完成 / 已作废 / 还是草稿