如何将 UniConsent CMP SDK 集成到 React Native 中

如何将 UniConsent CMP SDK 集成到 React Native 中

本指南介绍如何将 UniConsent CMP SDK 集成到您的 React Native 应用程序中,用于处理 GDPR IAB TCF 2.3 同意管理。

您可以在 SDK 软件包附带的 UniConsentDemo 目录中找到集成了此 SDK 的演示应用。

前提条件

  • 包含移动应用支持的 UniConsent CMP 计划。
  • React Native 版 UniConsent SDK 软件包(例如 uniconsent-react-native-sdk-26.2.0.zip),可从 UniConsent 控制面板下载或联系支持团队获取。
  • 可用的 React Native 开发环境。

快速开始(安装)

安装 SDK 软件包

下载并解压 SDK 软件包(例如 uniconsent-react-native-sdk-26.2.0.zip)。其中包含:

  • uniconsent-react-native-sdk-26.2.0.tgz — 可通过 npm 安装的 SDK 软件包
  • uniconsent-sdk/ — 预构建的 SDK 库文件
  • UniConsentDemo/ — 演示应用
  • README.md — 文档

使用 npm 或 Yarn 安装 .tgz 文件:

# Replace <path-to-package-file.tgz> with the actual path to the file
npm install <path-to-package-file.tgz>
# or
yarn add <path-to-package-file.tgz>

示例:如果您将 .tgz 文件放在项目根目录:

npm install ./uniconsent-react-native-sdk-26.2.0.tgz
# or
yarn add file:./uniconsent-react-native-sdk-26.2.0.tgz

安装对等依赖

此 SDK 需要以下对等依赖:

npm install react-native-webview react-native-default-preference
# or
yarn add react-native-webview react-native-default-preference

安装 iOS Pods

如果为 iOS 开发,请导航到项目的 ios 目录并安装 pods:

cd ios
pod install
cd ..

自定义同意界面

在集成 SDK 之前,请在 UniConsent 控制面板 中自定义同意横幅的外观,使其与您的品牌一致并优化同意率。

步骤 1:在控制面板中设置品牌样式

前往 Projects → 选择您的项目 → Settings → Step 5: UI & Style Settings 进行配置:

  • Main Button Colour — 设置主操作按钮颜色以匹配您的品牌
  • Main Button Text Colour — 调整主按钮上的文字颜色以确保可读性
  • Background Colour — 设置横幅背景颜色以融入您的应用
  • Text Colour — 确保正文文字具有适当的对比度

步骤 2:使用自定义 CSS 进行高级样式设置(可选)

如需更精确的控制,请在 Step 5 的 CSS Content 字段中添加自定义 CSS。建议通过此方式使横幅在您的应用中看起来更加原生,以获得最佳同意率:

/* Example: Style the accept button to match your brand */
.unic-btn-accept {
  background-color: #4CAF50;
  border-radius: 8px;
  font-weight: 600;
}

/* Example: Adjust banner font */
.unic-banner {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* Example: Make the reject button less prominent */
.unic-btn-reject {
  background-color: transparent;
  border: 1px solid #ccc;
  color: #666;
}

提示: 精心设计品牌风格的同意界面通常能获得更高的同意率。用户更愿意与符合他们期望的外观和风格的横幅积极互动。

使用方法

通过 Provider 初始化 SDK

使用 UniConsentProvider 包裹您应用的根组件(或相关部分)。您必须提供 licenseId(UniConsent 的 Publisher ID/pid)。

// Your main App file (e.g., App.tsx or index.js)
import React from 'react';
import { UniConsentProvider } from 'uniconsent-sdk';
import YourAppRootComponent from './src/YourAppRootComponent';

const App = () => {
  return (
    <UniConsentProvider licenseId="YOUR_LICENSE_ID">
      <YourAppRootComponent />
    </UniConsentProvider>
  );
};

export default App;

显示模式

SDK 支持三种 CMP 界面显示模式,通过 UniConsentProvider 上的 displayMode 属性配置:

模式说明
'fullScreen'全屏页面**(默认)**
'bottomSheet'锚定在屏幕底部的模态面板
'dialog'居中模态对话框
// Full screen (default — no prop needed)
<UniConsentProvider licenseId="YOUR_LICENSE_ID">

// Bottom sheet
<UniConsentProvider licenseId="YOUR_LICENSE_ID" displayMode="bottomSheet">

// Center dialog
<UniConsentProvider licenseId="YOUR_LICENSE_ID" displayMode="dialog">

事件处理

使用 UniConsentProvider 上的 onEvent 属性监听 SDK 生命周期事件。

可用事件类型:

  • 'sdkInit' — SDK 初始化开始
  • 'ready' — SDK 初始化完成
  • 'uiDisplay' — 同意界面已显示
  • 'uiClose' — 同意界面已关闭
<UniConsentProvider
  licenseId="YOUR_LICENSE_ID"
  onEvent={(event) => {
    switch (event.type) {
      case 'ready':
        console.log('SDK ready');
        break;
      case 'uiClose':
        console.log('Consent UI closed');
        break;
    }
  }}
>
  <YourAppRootComponent />
</UniConsentProvider>

显示 CMP 界面

在 Provider 内部的组件中使用 useConsent hook 获取 openCMP 函数,然后在需要时调用(例如按钮点击时)。

import React from 'react';
import { View, Text, Button, ActivityIndicator } from 'react-native';
import { useConsent } from 'uniconsent-sdk';

const ConsentInfoComponent = () => {
  const { consentStatus, isLoading, openCMP } = useConsent();

  return (
    <View>
      <Text>Consent Status:</Text>
      {isLoading ? (
        <ActivityIndicator />
      ) : (
        <Text>{consentStatus ?? 'Initializing...'}</Text>
      )}
      <Button
        title="Manage Privacy Settings"
        onPress={openCMP}
        disabled={isLoading}
      />
    </View>
  );
};

以编程方式检查同意状态

使用实用函数直接检查同意状态,无需使用 hook:

import {
  getTCString,
  isEURegion,
  isPurposeConsented,
  isVendorConsented,
  getConsentData,
} from 'uniconsent-sdk';

// Get the full TC String
const tcString = await getTCString();

// Check if user is in EU/EEA region
const inEU = await isEURegion();

// Check if a specific TCF purpose has consent (1-based ID)
const hasPurpose1 = await isPurposeConsented(1);

// Check if a specific vendor has consent (1-based ID)
const hasVendor755 = await isVendorConsented(755);

// Get all consent data as a single object
const consentData = await getConsentData();

将同意同步到 WebView

如果您的应用打开了一个加载带有 UniConsent CMP 标签的网页的 WebView,您可以传递原生同意状态,这样 CMP 标签会识别现有的同意,不会再次显示横幅。

使用 getConsentSyncScript() 配合 injectedJavaScriptBeforeContentLoaded 在任何页面脚本运行之前注入同意信息:

import React, { useState, useEffect } from 'react';
import { WebView } from 'react-native-webview';
import { getConsentSyncScript } from 'uniconsent-sdk';

const MyWebView = () => {
  const [consentScript, setConsentScript] = useState<string | null>(null);

  useEffect(() => {
    getConsentSyncScript().then(setConsentScript);
  }, []);

  if (!consentScript) return null;

  return (
    <WebView
      source={{ uri: 'https://example.com' }}
      injectedJavaScriptBeforeContentLoaded={consentScript}
    />
  );
};

调试工具

SDK 提供了用于开发和调试的辅助函数:

import { listKV, clearKV } from 'uniconsent-sdk';

// Log all stored consent keys to console
await listKV();

// Clear all stored consent data
await clearKV();

配置

UniConsentProvider 属性

属性类型必填默认值说明
licenseIdstring您的 UniConsent Publisher ID (pid)。
displayModeCMPDisplayMode'fullScreen'CMP 显示样式:'fullScreen''bottomSheet''dialog'
onEventCMPEventCallbackSDK 生命周期事件回调(sdkInitreadyuiDisplayuiClose)。

API 参考

组件和 Hooks

导出说明
UniConsentProvider用于包裹应用的 React 组件。需要 licenseId 属性。
useConsent()返回 { consentStatus, isLoading, openCMP } 的 Hook。

实用函数

函数返回值说明
getTCString()Promise<string>获取 IAB TCF 同意字符串。
isEURegion()Promise<boolean>检查用户是否在 EU/EEA 区域。
isPurposeConsented(purposeId)Promise<boolean>检查特定 TCF 目的的同意状态(基于 1 的 ID)。
isVendorConsented(vendorId)Promise<boolean>检查特定 TCF 供应商的同意状态(基于 1 的 ID)。
getConsentData()Promise<ConsentData>获取完整的同意数据对象。
getConsentSyncScript()Promise<string>获取用于向 WebView 注入同意信息的 JS 代码片段。
listKV()Promise<void>调试:将所有存储的同意键输出到控制台。
clearKV()Promise<void>调试:清除所有存储的同意数据。

导出类型

类型说明
CMPDisplayMode'fullScreen' | 'bottomSheet' | 'dialog'
CMPEventType'sdkInit' | 'ready' | 'uiDisplay' | 'uiClose'
CMPEventCallback(event: { type: CMPEventType }) => void
ConsentContextValueuseConsent() 返回值的类型定义。
ConsentDatagetConsentData() 返回值的类型定义。

ConsentData 字段

字段类型说明
tcStringstring完整的 IAB TCF 同意字符串。
isEURegionboolean用户是否在 EU/EEA 区域。
gdprAppliesbooleanGDPR 是否适用标志。
cmpSdkIdnumber注册的 CMP SDK ID(UniConsent 为 68)。
cmpSdkVersionnumberCMP SDK 版本。
policyVersionnumberTCF 政策版本。
purposeConsentsstring已同意目的的二进制字符串(例如 "10110")。
vendorConsentsstring已同意供应商的二进制字符串。
additionalConsentstringGoogle Additional Consent (AC) 字符串。
gvlVersionnumber使用的 Global Vendor List 版本。

注意事项

  • 隐私设置访问: 您的应用应为用户提供一种持久的方式(例如在设置菜单中放置"隐私设置"按钮或链接)来访问和更新他们的同意选择。此按钮应调用从 useConsent hook 获取的 openCMP() 函数。
  • 自动同意检查: UniConsentProvider 在应用启动时会自动检查同意状态,包括自用户上次授予同意以来 Global Vendor List (GVL) 是否已更新。如果 GVL 版本发生变化,将重新提示用户。