跳转到正文

Channel API 端点

GitHub

Channel 是 Capgo 中管理应用更新的核心机制。在自托管模式下,你需要实现 Channel 接口,以处理设备分配、Channel 查询和 Channel 管理操作。

Channels 可以让你:

  • 控制更新发布:为不同的用户群分配不同的 App 版本
  • A/B 测试:针对特定用户群体测试新功能
  • 分阶段发布:逐步发布更新以降低风险
  • 环境隔离:隔离开发、测试和生产环境的更新

在您的中配置 channel 端点 URL capacitor.config.json:

{
"plugins": {
"CapacitorUpdater": {
"channelUrl": "https://myserver.com/api/channel_self"
}
}
}

该插件会执行多种 channel 操作,您的端点需要处理这些操作:

当插件调用 listChannels(),它会发送一个 GET 请求来获取所有与设备兼容的 channels。这会返回与设备环境(dev/prod, emulator/real device)匹配,且允许公开访问或自行分配的 channels。

// GET /api/channel_self
// Headers:
{
"Content-Type": "application/json"
}
// Query parameters:
interface ListChannelsRequest {
app_id: string
platform: "ios" | "android" | "electron"
is_emulator: boolean
is_prod: boolean
key_id?: string
}
[
{
"id": 1,
"name": "production",
"public": true,
"allow_self_set": false
},
{
"id": 2,
"name": "beta",
"public": false,
"allow_self_set": true
}
]

响应中会包含每个频道的两个重要标志位:

  • public: true:这是一个 默认 channel. 设备无法通过以下方式自行分配到该通道: setChannel()。相反,如果设备移除其频道分配(使用 unsetChannel()),只要符合设备条件,它就会自动从该公共频道接收更新。

  • allow_self_set: true:这是一个 可自行分配的 Channel. 设备可以通过以下方式显式地将自己分配到此 Channel: setChannel(). 这适用于 Beta 测试、A/B 测试,或让用户选择加入特定的更新轨道。

当插件调用 getChannel(),它会发送一个 PUT 请求来获取设备当前分配的 channel。

// PUT /api/channel_self
// Headers:
{
"Content-Type": "application/json"
}
// Body:
interface GetChannelRequest {
device_id: string
app_id: string
platform: "ios" | "android" | "electron"
plugin_version: string
version_build: string
version_code: string
version_name: string
is_emulator: boolean
is_prod: boolean
defaultChannel?: string
channel?: string // For newer plugin versions, contains local channel override
}
{
"status": "ok",
"channel": "production",
"allowSet": true,
"message": "",
"error": ""
}

当插件调用 setChannel(),它会发送一个 POST 请求将设备分配到特定的 channel。

// POST /api/channel_self
interface SetChannelRequest {
device_id: string
app_id: string
channel: string
platform: "ios" | "android" | "electron"
plugin_version: string
version_build: string
version_code: string
version_name: string
is_emulator: boolean
is_prod: boolean
}
{
"status": "ok",
"message": "Device assigned to channel successfully",
"error": ""
}

当设备尝试将自身分配到一个 公开 channel (即包含 public: true) 时,您的 endpoint 应返回错误:

{
"status": "error",
"error": "public_channel_self_set_not_allowed",
"message": "This channel is public and does not allow device self-assignment. Unset the channel and the device will automatically use the public channel."
}

当设备尝试分配到一个不允许自我分配的 channel 时:

{
"status": "error",
"error": "channel_self_set_not_allowed",
"message": "This channel does not allow devices to self associate"
}

当插件调用 unsetChannel(),它会发送一个 DELETE 请求来移除设备的 channel 分配。

// DELETE /api/channel_self
interface UnsetChannelRequest {
device_id: string
app_id: string
platform: "ios" | "android" | "electron"
plugin_version: string
version_build: string
version_code: string
version_name: string
}

以下是实现 channel 端点的 JavaScript 示例:

interface ChannelRequest {
device_id: string
app_id: string
channel?: string
platform: "ios" | "android" | "electron"
plugin_version: string
version_build: string
version_code: string
version_name: string
}
interface ChannelResponse {
status: "ok" | "error"
channel?: string
allowSet?: boolean
message?: string
error?: string
}
export const handler = async (event) => {
const method = event.httpMethod || event.method
const body = JSON.parse(event.body || '{}') as ChannelRequest
const { device_id, app_id, channel, platform } = body
try {
switch (method) {
case 'GET':
return await getDeviceChannel(device_id, app_id)
case 'POST':
return await setDeviceChannel(device_id, app_id, channel!, platform)
case 'DELETE':
return await unsetDeviceChannel(device_id, app_id)
default:
return {
status: "error",
error: "Method not allowed"
}
}
} catch (error) {
return {
status: "error",
error: error.message
}
}
}
async function getDeviceChannel(deviceId: string, appId: string): Promise<ChannelResponse> {
// Query your database for device channel assignment
const assignment = await database.getDeviceChannel(deviceId, appId)
if (assignment) {
return {
status: "ok",
channel: assignment.channel,
allowSet: assignment.allowSelfAssign
}
}
// Return default channel if no assignment found
return {
status: "ok",
channel: "production", // Your default channel
allowSet: true
}
}
async function setDeviceChannel(
deviceId: string,
appId: string,
channel: string,
platform: string
): Promise<ChannelResponse> {
// Validate channel exists and allows self-assignment
const channelConfig = await database.getChannelConfig(channel, appId)
if (!channelConfig) {
return {
status: "error",
error: "Channel not found"
}
}
if (!channelConfig.allowDeviceSelfSet) {
return {
status: "error",
error: "Channel does not allow self-assignment"
}
}
// Check platform restrictions
if (platform === "ios" && !channelConfig.ios) {
return {
status: "error",
error: "Channel not available for iOS"
}
}
if (platform === "android" && !channelConfig.android) {
return {
status: "error",
error: "Channel not available for Android"
}
}
if (platform === "electron" && !channelConfig.electron) {
return {
status: "error",
error: "Channel not available for Electron"
}
}
// Save the assignment
await database.setDeviceChannel(deviceId, appId, channel)
return {
status: "ok",
message: "Device assigned to channel successfully"
}
}
async function unsetDeviceChannel(deviceId: string, appId: string): Promise<ChannelResponse> {
// Remove device channel assignment
await database.removeDeviceChannel(deviceId, appId)
return {
status: "ok",
message: "Device channel assignment removed"
}
}

你的 Channel 系统应支持以下配置选项:

interface ChannelConfig {
name: string
appId: string
// Platform targeting
ios: boolean // Allow updates to iOS devices
android: boolean // Allow updates to Android devices
electron: boolean // Allow updates to Electron apps
// Device type restrictions
allow_emulator: boolean // Allow updates on emulator/simulator devices
allow_device: boolean // Allow updates on real/physical devices
// Build type restrictions
allow_dev: boolean // Allow updates on development builds (is_prod=false)
allow_prod: boolean // Allow updates on production builds (is_prod=true)
// Channel assignment
public: boolean // Default channel - devices fall back to this when no override
allowDeviceSelfSet: boolean // Allow devices to self-assign via setChannel()
// Update policies
disableAutoUpdate: "major" | "minor" | "version_number" | "none"
disableAutoUpdateUnderNative: boolean
}

在列出兼容的 Channel 时(GET 请求),你应根据以下条件过滤 Channel:

  1. 平台检查:Channel 必须允许该设备的平台(ios, android,或 electron)
  2. 设备类型检查:
    • 如果 is_emulator=true: Channel 必须包含 allow_emulator=true
    • 如果 is_emulator=false: Channel 必须包含 allow_device=true
  3. Build 类型检查:
    • 如果 is_prod=true: Channel 必须包含 allow_prod=true
    • 如果 is_prod=false: Channel 必须包含 allow_dev=true
  4. 可见性检查: Channel 必须为 public=true 或者 allow_device_self_set=true
// Example filtering logic
function getCompatibleChannels(
platform: 'ios' | 'android' | 'electron',
isEmulator: boolean,
isProd: boolean,
channels: ChannelConfig[]
): ChannelConfig[] {
return channels.filter(channel => {
// Platform check
if (!channel[platform]) return false
// Device type check
if (isEmulator && !channel.allow_emulator) return false
if (!isEmulator && !channel.allow_device) return false
// Build type check
if (isProd && !channel.allow_prod) return false
if (!isProd && !channel.allow_dev) return false
// Must be accessible (public or self-assignable)
if (!channel.public && !channel.allowDeviceSelfSet) return false
return true
})
}

你需要存储 channel 配置和设备分配信息:

-- Channels table
CREATE TABLE channels (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
app_id VARCHAR(255) NOT NULL,
-- Platform targeting
ios BOOLEAN DEFAULT true,
android BOOLEAN DEFAULT true,
electron BOOLEAN DEFAULT true,
-- Device type restrictions
allow_emulator BOOLEAN DEFAULT true, -- Allow emulator/simulator devices
allow_device BOOLEAN DEFAULT true, -- Allow real/physical devices
-- Build type restrictions
allow_dev BOOLEAN DEFAULT true, -- Allow development builds
allow_prod BOOLEAN DEFAULT true, -- Allow production builds
-- Channel assignment
public BOOLEAN DEFAULT false, -- Default channel (fallback)
allow_device_self_set BOOLEAN DEFAULT false, -- Allow self-assignment
-- Update policies
disable_auto_update VARCHAR(50) DEFAULT 'none',
disable_auto_update_under_native BOOLEAN DEFAULT false,
created_at TIMESTAMP DEFAULT NOW(),
UNIQUE(name, app_id)
);
-- Device channel assignments table
CREATE TABLE device_channels (
id SERIAL PRIMARY KEY,
device_id VARCHAR(255) NOT NULL,
app_id VARCHAR(255) NOT NULL,
channel_name VARCHAR(255) NOT NULL,
assigned_at TIMESTAMP DEFAULT NOW(),
UNIQUE(device_id, app_id)
);

处理常见的错误场景:

// Channel not found
{
"status": "error",
"error": "Channel 'beta' not found"
}
// Self-assignment not allowed
{
"status": "error",
"error": "Channel does not allow device self-assignment"
}
// Platform not supported
{
"status": "error",
"error": "Channel not available for this platform"
}
// Invalid request
{
"status": "error",
"error": "Missing required field: device_id"
}
  1. 安全: 根据业务规则校验所有渠道分配
  2. 日志记录: 记录所有渠道操作,以便审计和调试
  3. 性能: 缓存渠道配置以减少数据库查询
  4. 验证: 验证 device_id 和 app_id 的真实性
  5. 速率限制: 实施速率限制以防止滥用

渠道分配会与您的 更新 API 端点当设备请求更新时,请检查其分配的 channel,以确定应提供哪个版本:

async function getUpdateForDevice(deviceId: string, appId: string) {
// Get device's channel assignment
const channelAssignment = await getDeviceChannel(deviceId, appId)
const channel = channelAssignment.channel || 'production'
// Get the version assigned to this channel
const channelVersion = await getChannelVersion(channel, appId)
return {
version: channelVersion.version,
url: channelVersion.url,
checksum: channelVersion.checksum
}
}

这将构建一套完整的自托管 channel 管理系统,让您能够完全掌控更新分发给用户的方式。

从 Channel API 端点继续

标题为“从 Channel API 端点继续

如果你正在使用 Channel API 端点 要规划 Channel 路由和分阶段发布,请将其与 使用 @capgo/capacitor-updater 用于“使用 @capgo/capacitor-updater”中的原生能力, 通道 有关 Channels 的实现细节, 通道 有关 Channels 的实现细节, 通道 有关 Channels 的实现细节,以及 Beta 测试解决方案 Beta Testing Solution 的产品工作流。