# @azure/communication-common 中文文档

规范地址：https://npmcn.com/package/%40azure/communication-common/

版本：2\.5\.0
npm 元数据更新时间：2026-08-04T19:04:06.809Z
中文译文更新时间：2026-11-07T12:51:56.097Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40azure/communication-common
原文对照：https://npmcn.com/package/%40azure/communication-common/?lang=original
项目主页：https://github.com/Azure/azure-sdk-for-js/tree/main/sdk/communication/communication-common/README.md
源码仓库：https://github.com/Azure/azure-sdk-for-js

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：635 kB，248 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=22\.0\.0
- 运行依赖：10 个
- 首次发布：2020-09-22T06:05:52.317Z
- 最新版本发布：2026-08-04T19:04:06.566Z
- 近 30 天下载量：3092934（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：406（近 12 个月 42 个）

## 中文简介

Azure通信服务共同软件包.

## 安装

```sh
npm install @azure/communication-common
```

也可以使用：`pnpm add @azure/communication-common`、`yarn add @azure/communication-common`、`bun add @azure/communication-common`

## README

# 用于 JavaScript 的 Azure 通信普通客户端库

这个包包含了Azure通信服务库的通用代码.

## 开始

### 先决条件

-   一个 [Azure 订阅](https://azure.microsoft.com/free/)。 。 。 .
-   现有通信服务资源。 如果您需要创建资源, 您可以使用 [Azure 门户](https://portal.azure.com/),则 [Azure 动力壳](https://learn.microsoft.com/powershell/module/az.communication/new-azcommunicationservice),或 [阿苏尔CLI](https://learn.microsoft.com/cli/azure)。 。 。 .
-   安装了 @azure/ 身份包 .

### 安装

```bash
npm install @azure/communication-common
```

```bash
npm install @azure/identity
```

### 浏览器支持

#### Java 脚本套装

要在浏览器中使用此客户端库,首先需要使用捆绑器. 关于如何做到这一点的详情,请参见我们 [捆绑文件](https://aka.ms/AzureSDKBundling)。 。 。 .

## 关键概念

### 信用通讯和Azure通讯 证书

这个 `CommunicationTokenCredential` 是一个用于认证用户与通信服务的接口,例如聊天或呼叫.

这个 `AzureCommunicationTokenCredential` 提供了一种方便的方法来创建执行上述接口的证书,并允许您利用内置的自动更新逻辑.

根据你的情况,你可能想要初始化 `AzureCommunicationTokenCredential` 改为:

-   静态符号(适用于短寿命客户端,例如发送一次性聊天信息)或
-   一个可确保通信中持续认证状态的回调功能(理想的,如长调会话).
-   能够获取 Entra 用户令牌的证书。 您可以提供执行 [Token 证书界面](https://learn.microsoft.com/es-mx/javascript/api/@azure/core-auth/tokencredential?view=azure-node-latest)。它适合需要Entra用户访问令牌与通信服务进行认证的情况.

给 `AzureCommunicationTokenCredential` 可以通过构建器或通过符号再生回调,可以通过Azure通信身份库获得.

## 实例

### 用静态符号创建证书

对于寿命短的客户来说,到期后刷新信使是不必要的,而且 `AzureCommunicationTokenCredential` 可能用静态符号进行即时处理.

```ts
import { AzureCommunicationTokenCredential } from "@azure/communication-common";

const tokenCredential = new AzureCommunicationTokenCredential(
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjM2MDB9.adM-ddBZZlQ1WlN3pdPBOF5G4Wh9iZpxNP_fSvpF4cWs",
);
```

### 创建带有召回的证书

在这里,我们假设我们有一个功能 `fetchTokenFromMyServerForUser` 以获取 JWT 符号字符串。 我们把它传到证书 给鲍勃从自己的服务器取个信物 我们的服务器会使用 Azure 通讯身份库 来发行信使。 有必要让 `fetchTokenFromMyServerForUser` 函数返回一个有效的符号(在未来设定了过期日期).

```ts
import { AzureCommunicationTokenCredential } from "@azure/communication-common";

function fetchTokenFromMyServerForUser(user: string): Promise<string> {
  // Your custom implementation to fetch a token for the user
  return Promise.resolve("some-unique-token-for-" + user);
}

const tokenCredential = new AzureCommunicationTokenCredential({
  tokenRefresher: async () => fetchTokenFromMyServerForUser("bob@contoso.com"),
});
```

### 创建具有主动更新的证书

设置 `refreshProactively` {\\fn黑体\\fs22\\bord1\\shad0\\3ahbe\\4ah00\\fscx67\\fscy66\\2chffffff\\3ch808080}真的会叫你的 `tokenRefresher` 当符号接近过期时,函数.

```ts
import { AzureCommunicationTokenCredential } from "@azure/communication-common";

function fetchTokenFromMyServerForUser(user: string): Promise<string> {
  // Your custom implementation to fetch a token for the user
  return Promise.resolve("some-unique-token-for-" + user);
}

const tokenCredential = new AzureCommunicationTokenCredential({
  tokenRefresher: async () => fetchTokenFromMyServerForUser("bob@contoso.com"),
  refreshProactively: true,
});
```

### 创建具有主动更新和初始符号的证书

通过 `initialToken` 是一个可选的优化以跳过第一个调用到 `tokenRefresher`。您可以使用此工具将启动器与您的应用程序与随后的符号刷新周期区分开来.

```ts
import { AzureCommunicationTokenCredential } from "@azure/communication-common";

function fetchTokenFromMyServerForUser(user: string): Promise<string> {
  // Your custom implementation to fetch a token for the user
  return Promise.resolve("some-unique-token-for-" + user);
}

const tokenCredential = new AzureCommunicationTokenCredential({
  tokenRefresher: async () => fetchTokenFromMyServerForUser("bob@contoso.com"),
  refreshProactively: true,
  token:
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjM2MDB9.adM-ddBZZlQ1WlN3pdPBOF5G4Wh9iZpxNP_fSvpF4cWs",
});
```

### 为加密或不透明的访问令牌创建证书

一些访问令牌——如发给企业Entra用户的令牌——是加密的,无法在客户端上解码,因此证书无法读取其过期. 建议的办法是返回 `AccessToken` (单位:千美元)`{ token, expiresOnTimestamp }`从你的 `tokenRefresher` (或通过一个作为初始) `token`),设置 `expiresOnTimestamp` 从符号响应的 `expires_in`。这保持了主动更新时间安排的准确性.

```ts
import { AzureCommunicationTokenCredential } from "@azure/communication-common";

// Some access tokens (e.g. for enterprise Entra users) are encrypted and cannot be
// decoded on the client. Return an AccessToken with an explicit expiry so proactive
// refresh scheduling stays accurate; derive expiresOnTimestamp from the response's expires_in.
async function fetchEncryptedTokenForUser(user: string): Promise<{
  token: string;
  expiresOnTimestamp: number;
}> {
  const response = { token: "some-encrypted-token-for-" + user, expiresInSeconds: 8 * 60 * 60 };
  return {
    token: response.token,
    expiresOnTimestamp: Date.now() + response.expiresInSeconds * 1000,
  };
}

const tokenCredential = new AzureCommunicationTokenCredential({
  tokenRefresher: async () => fetchEncryptedTokenForUser("bob@contoso.com"),
  refreshProactively: true,
});
```

如果你只能提供符号字符串,证书人会接受它并假设一个倒置寿命. 设定 `undecodableTokenExpiryIntervalInSeconds` 这样它们就不会比需要的更频繁地被刷新; 它默认为600秒.

```ts
import { AzureCommunicationTokenCredential } from "@azure/communication-common";

function fetchOpaqueTokenForUser(user: string): Promise<string> {
  // Your custom implementation returns an opaque token string that can't be decoded.
  return Promise.resolve("some-opaque-token-for-" + user);
}

const tokenCredential = new AzureCommunicationTokenCredential({
  tokenRefresher: async () => fetchOpaqueTokenForUser("bob@contoso.com"),
  refreshProactively: true,
  // When the token can't be decoded and no explicit expiry is provided, assume this
  // lifetime (in seconds) instead of the 600s default — set it to your tokens' real lifetime.
  undecodableTokenExpiryIntervalInSeconds: 3600,
});
```

### 以能够获取 Entra 用户令牌的证书创建证书

对于Entra用户可用于通信服务的情景,您需要初始化任何执行 [Token 证书界面](https://learn.microsoft.com/es-mx/javascript/api/@azure/core-auth/tokencredential?view=azure-node-latest) 并提供给 `EntraCommunicationTokenCredentialOptions`。 。 。 . 在此同时, 您必须提供 Azure 通信服务的 URI 资源以及 Entra 用户代号所需的范围 。 这些范围决定了给令牌的许可.

这种方法需要用于授权一个持有Teams许可证的Entra用户通过你的Azure通信服务资源使用Teams Phone扩展功能. 这需要提供 `https://auth.msft.communication.azure.com/TeamsExtension.ManageCalls` 范围。 对于海合会云环境,使用 `https://auth.msft.communication.azure.us/TeamsExtension.ManageCalls`。 。 。 .

```ts
import { InteractiveBrowserCredential } from "@azure/identity";
import {
  EntraCommunicationTokenCredentialOptions,
  AzureCommunicationTokenCredential,
} from "@azure/communication-common";

const options = {
  tenantId: "<your-tenant-id>",
  clientId: "<your-client-id>",
  redirectUri: "<your-redirect-uri>",
};
const entraTokenCredential = new InteractiveBrowserCredential(options);

const entraTokenCredentialOptions: EntraCommunicationTokenCredentialOptions = {
  resourceEndpoint: "https://<your-resource>.communication.azure.com",
  tokenCredential: entraTokenCredential,
  scopes: ["https://auth.msft.communication.azure.com/TeamsExtension.ManageCalls"],
};

const credential = new AzureCommunicationTokenCredential(entraTokenCredentialOptions);
```

Entra用户利用Azure通信服务的其他设想方案目前处于 **仅预览阶段,不应用于生产**。 。 。 . 这些设想方案的范围遵循格式 `https://communication.azure.com/clients/<ACS Scope>`如果不提供特定范围,默认范围将被设定为 `https://communication.azure.com/clients/.default`。 。 。 .

```ts
import { InteractiveBrowserCredential } from "@azure/identity";
import {
  EntraCommunicationTokenCredentialOptions,
  AzureCommunicationTokenCredential,
} from "@azure/communication-common";

const options = {
  tenantId: "<your-tenant-id>",
  clientId: "<your-client-id>",
  redirectUri: "<your-redirect-uri>",
};
const entraTokenCredential = new InteractiveBrowserCredential(options);

const entraTokenCredentialOptions: EntraCommunicationTokenCredentialOptions = {
  resourceEndpoint: "https://<your-resource>.communication.azure.com",
  tokenCredential: entraTokenCredential,
  scopes: ["https://communication.azure.com/clients/VoIP"],
};

const credential = new AzureCommunicationTokenCredential(entraTokenCredentialOptions);
```

## 解决问题

-   **指定无效的符号**:确保你传递给 `AzureCommunicationTokenCredential` 构造器或 `tokenRefresher` 召回是一个赤裸的JWT符号字符串. 例如,如果你在使用 [Azure 通信身份图书馆](https://learn.microsoft.com/javascript/api/@azure/communication-identity/communicationaccesstoken#@azure-communication-identity-communicationaccesstoken-token) 或者说 [(原始内容存档于2013-10-12) (英语). REST API](https://learn.microsoft.com/rest/api/communication/communication-identity/issue-access-token#communicationidentityaccesstoken) 保证你刚刚通过 `token` 部分响应对象.

### 日志

允许伐木可能有助于发现有关失败的有用信息。 为了查看 HTTP 请求和回复的日志,设置 `AZURE_LOG_LEVEL` 环境变量改为 `info`。或者,可以在运行时拨打 `setLogLevel` 输入 `@azure/logger`数字 :

```ts
import { setLogLevel } from "@azure/logger";

setLogLevel("info");
```

## 今后的步骤

-   [更多信息: 通讯用户访问符](https://learn.microsoft.com/azure/communication-services/concepts/authentication?tabs=javascript)

## 捐款

如果您想为图书馆捐钱 请读一下 [贡献指南](https://github.com/Azure/azure-sdk-for-js/blob/main/CONTRIBUTING.md) 学习如何构建和测试密码.

## 相关项目

-   [Microsoft Azure SDK 用于 Javascript](https://github.com/Azure/azure-sdk-for-js)

## 常见问题

### @azure/communication-common 是什么？

Azure通信服务共同软件包\.

### 如何安装 @azure/communication-common？

在项目目录运行 npm install @azure/communication-common，或使用 pnpm add / yarn add / bun add。

### @azure/communication-common 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @azure/communication-common 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @azure/communication-common 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=22\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @azure/communication-common 可以商用吗？

@azure/communication-common 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @azure/communication-common 的下载量有多少？

根据 npm 官方下载统计，@azure/communication-common 在 2026/10/08 – 2026/11/06 这 30 天内被下载 3,092,934 次，日均约 103,098 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @azure/communication-common 还在维护吗？

最新版本 2\.5\.0 发布于 2026/08/05（3 个月前）；至今共发布 406 个版本，其中过去 12 个月发布了 42 个；首次发布于 2020/09/22。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

