API Signing Examples

Complete SignRecipient (API Signing) calls: get an access_token, fetch the JWKS key, build the JWE Credential, then call the signing endpoint.

Endpoint reference: Sign Recipient (SignRecipient).

Prerequisites

  • The envelope is sent and contains a signing control for this signer (e.g. signHere)
  • The signer has configured a Signing PIN and has accepted the ERSD disclosure (first-time consent happens on the signing page)
  • The App has API integration enabled and the token carries the envelope:sign scope
ℹ️

Credential is not the PIN in plaintext: it is the PIN encrypted as a JWE (alg=RSA-OAEP-256, enc=A256GCM, 5-segment Compact). All six samples below build that encryption with their own standard library or official library, with no SDK from us.

All six samples walk through the same four steps and are ready to run.

Go

Dependencies:Go 1.20+ (crypto/rsa, crypto/cipher and net/http are all standard library)

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"
)
 
// production (Singapore); use https://api.test.sign.tencent.com for the test environment
const baseURL = "https://sgapi.tencent-esign.com"
 
const (
	clientID     = "SGCL..."
	clientSecret = "..."
	spaceID      = "SGSP..." // required in client_credentials mode
	operatorUID  = "SGUR..." // optional: the actual sender/operator (kept for the audit trail)
 
	envelopeID   = "SGEV..." // EnvelopeId returned by quick-create
	recipientID  = "r-1"     // the Signers[].RecipientId you set when creating the envelope
	recipientUID = "SGUR..." // the signer's user ID on this platform
	signingPIN   = "666666"  // the Signing PIN configured by this signer
	signatureID  = "SIG..."  // a signature ID from this signer's signature library (default asset)
)
 
var b64 = base64.RawURLEncoding
 
func main() {
	// (1) get an access_token (server to server; in authorization_code mode reuse your stored 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)
 
	// (2) fetch the JWKS encryption key (the use=enc key)
	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("no use=enc key in the JWKS")
	}
 
	// (3) build the JWE Credential (RSA-OAEP-256 + A256GCM, 5-segment 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))
 
	// (4) call the signing endpoint. The idempotency key is required: reuse the same value when retrying
	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))
}
 
// Encrypt the PIN into the Credential required by SignRecipient
// a credential lives 60 seconds and its jti is single-use: generate a new one for every call, including retries
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",
	})
	// this exact protected header is the AAD used below, keep the bytes unchanged
	protectedHeader := b64.EncodeToString(header)
 
	// random 32-byte CEK, wrapped with the server's RSA public key
	// the MGF1 digest must match the OAEP hash, SHA-256 here
	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 segments: protected.encryptedKey.iv.ciphertext.tag
	// the encryption output is ciphertext || tag; the trailing 16 bytes form their own segment
	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("failed to decode the response: %v (%s)", err, body))
	}
}

Python

Dependencies:Python 3.8+, cryptography (pip install cryptography)

"""Tencent eSign Global - SignRecipient (interface signing) example."""
 
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
 
# production (Singapore); use https://api.test.sign.tencent.com for the test environment
BASE_URL = "https://sgapi.tencent-esign.com"
 
CLIENT_ID = "SGCL..."
CLIENT_SECRET = "..."
SPACE_ID = "SGSP..."  # required in client_credentials mode
OPERATOR_USER_ID = "SGUR..."  # optional: the actual sender/operator (kept for the audit trail)
 
ENVELOPE_ID = "SGEV..."  # EnvelopeId returned by quick-create
RECIPIENT_ID = "r-1"  # the Signers[].RecipientId you set when creating the envelope
RECIPIENT_USER_ID = "SGUR..."  # the signer's user ID on this platform
SIGNING_PIN = "666666"  # the Signing PIN configured by this signer
SIGNATURE_ID = "SIG..."  # a signature ID from this signer's signature library (default asset)
 
 
def b64u(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()
 
 
def fetch_access_token() -> str:
    """(1) get an access_token (server to server; in authorization_code mode reuse your stored 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():
    """(2) fetch the JWKS encryption key (the use=enc key)"""
    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("no use=enc key in the JWKS")
 
 
def build_credential(public_key, kid: str) -> str:
    """(3) build the JWE Credential (RSA-OAEP-256 + A256GCM, 5-segment Compact)。
 
    a credential lives 60 seconds and its jti is single-use: generate a new one for every call, including retries
    """
    header = json.dumps(
        {"alg": "RSA-OAEP-256", "enc": "A256GCM", "kid": kid, "typ": "JWE"},
        separators=(",", ":"),
    ).encode()
    # this exact protected header is the AAD used below, keep the bytes unchanged
    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()
 
    # random 32-byte CEK, wrapped with the server's RSA public key
    # the MGF1 digest must match the OAEP hash, SHA-256 here
    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())
 
    # the encryption output is ciphertext || tag; the trailing 16 bytes form their own segment
    # JWE Compact, 5 segments: 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:
    """(4) call the signing endpoint. The idempotency key is required: reuse the same value when retrying"""
    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

Dependencies:JDK 11+, jackson-databind (JSON parsing only)

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 - minimal runnable SignRecipient (interface signing) example.
 *
 * Requires JDK 11+ and jackson-databind (JSON parsing only).
 *
 * Flow: (1) get an access_token, (2) fetch the JWKS encryption key, (3) build the JWE Credential locally, (4) call the signing endpoint.
 *
 * Note: the Credential is assembled as a JWE Compact by hand with plain JDK APIs, no JOSE library involved.
 * JOSE libraries disagree on the default MGF1 digest for RSA-OAEP-256 (some use SHA-1), which makes
 * decryption fail on the server side (surfaced as AUTH.CREDENTIAL_INVALID), so SHA-256 is set explicitly below.
 */
public class SignRecipientExample {
 
    // ===== fill in for your environment =====
    // production (Singapore); use https://api.test.sign.tencent.com for the test environment
    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..."; // required in client_credentials mode
    private static final String OPERATOR_USER_ID = "SGUR..."; // optional: the actual sender/operator (kept for the audit trail)
 
    private static final String ENVELOPE_ID = "SGEV..."; // EnvelopeId returned by quick-create
    private static final String RECIPIENT_ID = "r-1"; // the Signers[].RecipientId you set when creating the envelope
    private static final String RECIPIENT_USER_ID = "SGUR..."; // the signer's user ID on this platform
    private static final String SIGNING_PIN = "666666"; // the Signing PIN configured by this signer
    private static final String SIGNATURE_ID = "SIG..."; // a signature ID from this signer's signature library (default asset)
 
    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();
 
        // (1) get an access_token (server to server; in authorization_code mode reuse your stored 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();
 
        // (2) fetch the JWKS encryption key (the use=enc key)
        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("no use=enc key in the JWKS");
        }
        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()))));
 
        // (3) build the JWE Credential (RSA-OAEP-256 + A256GCM, 5-segment Compact)
        String credential = buildCredential(publicKey, jwk.path("kid").asText(),
                SIGNING_PIN, RECIPIENT_USER_ID, ENVELOPE_ID, RECIPIENT_ID);
 
        // (4) call the signing endpoint. The idempotency key is required: reuse the same value when retrying
        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("signing failed: " + 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());
    }
 
    /**
     * Encrypt the PIN into the Credential required by SignRecipient
     *
     * <p>a credential lives 60 seconds and its jti is single-use: generate a new one for every call, including retries
     * the three context values must match the path parameters and the signer exactly, or the credential is rejected</p>
     */
    private static String buildCredential(RSAPublicKey publicKey, String kid, String pin,
                                          String userId, String envelopeId, String recipientId) throws Exception {
        // this exact protected header is the AAD used below, keep the bytes unchanged
        String headerJson = "{\"alg\":\"RSA-OAEP-256\",\"enc\":\"A256GCM\",\"kid\":\"" + kid + "\",\"typ\":\"JWE\"}";
        String protectedHeader = B64.encodeToString(headerJson.getBytes(StandardCharsets.UTF_8));
 
        // random 32-byte CEK, wrapped with the server's RSA public key
        // the MGF1 digest must match the OAEP hash, SHA-256 here
        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);
 
        // plaintext payload
        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));
        // the encryption output is ciphertext || tag; the trailing 16 bytes form their own segment
        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

Dependencies:Node.js 18+ (built-in fetch and node:crypto)

import crypto from 'node:crypto';
 
// production (Singapore); use https://api.test.sign.tencent.com for the test environment
const BASE_URL = 'https://sgapi.tencent-esign.com';
 
const CLIENT_ID = 'SGCL...';
const CLIENT_SECRET = '...';
const SPACE_ID = 'SGSP...'; // required in client_credentials mode
const OPERATOR_USER_ID = 'SGUR...'; // optional: the actual sender/operator (kept for the audit trail)
 
const ENVELOPE_ID = 'SGEV...'; // EnvelopeId returned by quick-create
const RECIPIENT_ID = 'r-1'; // the Signers[].RecipientId you set when creating the envelope
const RECIPIENT_USER_ID = 'SGUR...'; // the signer's user ID on this platform
const SIGNING_PIN = '666666'; // the Signing PIN configured by this signer
const SIGNATURE_ID = 'SIG...'; // a signature ID from this signer's signature library (default asset)
 
const b64 = (buffer) => Buffer.from(buffer).toString('base64url');
 
// (1) get an access_token (server to server; in authorization_code mode reuse your stored 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;
}
 
// (2) fetch the JWKS encryption key (the use=enc key)
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('no use=enc key in the JWKS');
  return { kid: jwk.kid, publicKey: crypto.createPublicKey({ key: jwk, format: 'jwk' }) };
}
 
// (3) build the JWE Credential (RSA-OAEP-256 + A256GCM, 5-segment Compact)
// a credential lives 60 seconds and its jti is single-use: generate a new one for every call, including retries
function buildCredential(publicKey, kid) {
  const header = JSON.stringify({ alg: 'RSA-OAEP-256', enc: 'A256GCM', kid, typ: 'JWE' });
  // this exact protected header is the AAD used below, keep the bytes unchanged
  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(),
  });
 
  // random 32-byte CEK, wrapped with the server's RSA public key
  // the MGF1 digest must match the OAEP hash, SHA-256 here
  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('.');
}
 
// (4) call the signing endpoint. The idempotency key is required: reuse the same value when retrying
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)

Dependencies:.NET 8+ (System.Security.Cryptography built in)

using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
 
// production (Singapore); use https://api.test.sign.tencent.com for the test environment
const string BaseUrl = "https://sgapi.tencent-esign.com";
 
const string ClientId = "SGCL...";
const string ClientSecret = "...";
const string SpaceId = "SGSP..."; // required in client_credentials mode
const string OperatorUserId = "SGUR..."; // optional: the actual sender/operator (kept for the audit trail)
 
const string EnvelopeId = "SGEV..."; // EnvelopeId returned by quick-create
const string RecipientId = "r-1"; // the Signers[].RecipientId you set when creating the envelope
const string RecipientUserId = "SGUR..."; // the signer's user ID on this platform
const string SigningPin = "666666"; // the Signing PIN configured by this signer
const string SignatureId = "SIG..."; // a signature ID from this signer's signature library (default asset)
 
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
 
// (1) get an access_token (server to server; in authorization_code mode reuse your stored 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",
    }));
 
// (2) fetch the JWKS encryption key (the use=enc key)
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("no use=enc key in the JWKS");
}
 
using var rsa = RSA.Create();
rsa.ImportParameters(new RSAParameters
{
    Modulus = Base64UrlDecode(encryptionKey["n"]!.GetValue<string>()),
    Exponent = Base64UrlDecode(encryptionKey["e"]!.GetValue<string>()),
});
 
// (3) build the JWE Credential (RSA-OAEP-256 + A256GCM, 5-segment 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);
 
// (4) call the signing endpoint. The idempotency key is required: reuse the same value when retrying
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);
 
// Encrypt the PIN into the Credential required by SignRecipient
// a credential lives 60 seconds and its jti is single-use: generate a new one for every call, including retries
static string BuildCredential(RSA rsa, string kid, string payload)
{
    var header = new JsonObject
    {
        ["alg"] = "RSA-OAEP-256",
        ["enc"] = "A256GCM",
        ["kid"] = kid,
        ["typ"] = "JWE",
    }.ToJsonString();
    // this exact protected header is the AAD used below, keep the bytes unchanged
    var protectedHeader = Base64UrlEncode(Encoding.UTF8.GetBytes(header));
 
    // random 32-byte CEK, wrapped with the server's RSA public key
    // the MGF1 digest must match the OAEP hash, SHA-256 here
    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));
 
    // the encryption output is ciphertext || tag; the trailing 16 bytes form their own segment
    // JWE Compact, 5 segments: 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

Dependencies:PHP 7.4+ and phpseclib 3 (composer require phpseclib/phpseclib:~3.0) — the openssl extension cannot set the OAEP MGF1 digest, so RSA must go through phpseclib

<?php
 
/**
 * Tencent eSign Global - SignRecipient (interface signing) example.
 *
 * Requires PHP 7.4+ and phpseclib 3 (composer require phpseclib/phpseclib:~3.0)
 */
 
require __DIR__ . '/vendor/autoload.php';
 
use phpseclib3\Crypt\RSA;
 
// production (Singapore); use https://api.test.sign.tencent.com for the test environment
const BASE_URL = 'https://sgapi.tencent-esign.com';
 
const CLIENT_ID = 'SGCL...';
const CLIENT_SECRET = '...';
const SPACE_ID = 'SGSP...'; // required in client_credentials mode
const OPERATOR_USER_ID = 'SGUR...'; // optional: the actual sender/operator (kept for the audit trail)
 
const ENVELOPE_ID = 'SGEV...'; // EnvelopeId returned by quick-create
const RECIPIENT_ID = 'r-1'; // the Signers[].RecipientId you set when creating the envelope
const RECIPIENT_USER_ID = 'SGUR...'; // the signer's user ID on this platform
const SIGNING_PIN = '666666'; // the Signing PIN configured by this signer
const SIGNATURE_ID = 'SIG...'; // a signature ID from this signer's signature library (default asset)
 
// (1) get an access_token (server to server; in authorization_code mode reuse your stored 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');
 
// (2) fetch the JWKS encryption key (the use=enc key)
$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('no use=enc key in the JWKS');
}
 
// (3) build the JWE Credential (RSA-OAEP-256 + A256GCM, 5-segment Compact)
$credential = build_credential($jwk);
 
// (4) call the signing endpoint. The idempotency key is required: reuse the same value when retrying
$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;
 
// Encrypt the PIN into the Credential required by SignRecipient
// a credential lives 60 seconds and its jti is single-use: generate a new one for every call, including retries
function build_credential(array $jwk): string
{
    $header = json_encode([
        'alg' => 'RSA-OAEP-256',
        'enc' => 'A256GCM',
        'kid' => $jwk['kid'],
        'typ' => 'JWE',
    ], JSON_UNESCAPED_SLASHES);
    // this exact protected header is the AAD used below, keep the bytes unchanged
    $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);
 
    // random 32-byte CEK, wrapped with the server's RSA public key
    // the MGF1 digest must match the OAEP hash, SHA-256 here
    $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 encryption failed: ' . openssl_error_string());
    }
 
    // the encryption output is ciphertext || tag; the trailing 16 bytes form their own segment
    // JWE Compact, 5 segments: 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} failed");
    }
    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} failed");
    }
    return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}

Four Rules That Trip People Up

  • A credential lives 60 seconds and its jti is single-use: generate a new one for every call, including retries
  • The userId / envelopeId / recipientId in context must match the signer and the URL exactly; any mismatch is reported as the generic AUTH.CREDENTIAL_INVALID
  • The MGF1 digest for RSA-OAEP-256 must be SHA-256: some JOSE libraries default to SHA-1, which fails to decrypt. Set it explicitly
  • The idempotency key is required: reuse the same Idempotency-Key when retrying the same business request. Replaying a previously successful call returns the original result with IdempotentReplay=true and does not sign twice

Error Mapping

Start with a self-check that the public key is reachable:

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

It should return an RSA key with use=enc, kid and alg=RSA-OAEP-256. A 404 means the gateway does not expose /.well-known/*; contact us.

ErrorCheck first
AUTH.CREDENTIAL_REQUIREDno Credential in the body (plaintext PIN is not accepted by default; ask us to enable it for your App)
AUTH.CREDENTIAL_INVALIDjti reused; context values not matching the signer/URL; wrong alg/enc/kid; MGF1 not SHA-256; credential not 5 segments
AUTH.CREDENTIAL_EXPIREDmore than 60 seconds between encryption and the call, or client clock skew beyond 30 seconds
AUTH.PIN_NOT_CONFIGUREDthe signer has not set a Signing PIN yet
SIGNING.CONSENT_REQUIREDthe signer has not accepted the ERSD disclosure yet
SIGNING.SIGNATURE_REQUIREDthe envelope has no signing control, or the signer has no usable signing asset
INVALID_REQUESTmissing idempotency key (Idempotency-Key header or body IdempotencyKey)
RECIPIENT.NOT_RECIPIENTthe recipientId in the path is not a signer of this envelope
ENVELOPE.INVALID_STATUSenvelope completed / voided / still a draft