# Capacitor SDK 基础集成指南

本节包含有关如何将 Pushwoosh Capacitor SDK 集成到您的应用程序中的信息。

## 前提条件

要将 Pushwoosh Capacitor SDK 集成到您的应用中，您需要具备以下条件：

<Aside type="note" title="要求">
 - 一个 [Pushwoosh 账户](https://sso.pushwoosh.com/login)。
 - 在您的账户中设置一个 [Pushwoosh 项目](/zh/product/first-steps/start-with-your-project/create-your-project)。
 - **对于 iOS 集成：**
    - 一个配置为发送推送通知的 iOS 平台。我们建议使用 [基于令牌的身份验证配置](/zh/developer/first-steps/connect-messaging-services/ios-configuration/ios-token-based-configuration/) 作为最简单的方法。
    - 将网关设置为 `Sandbox` 以向模拟器发送推送。
 - **对于 Android 集成：**
    - 一个 [已配置的 Android 平台](/zh/developer/first-steps/connect-messaging-services/android-configuration/android-firebase-configuration)
    - 来自您的 Firebase 项目的 `google-services.json` 文件和 `package name`。
    - 一个连接到您的 Android 应用程序的 Firebase 项目。如果需要，请遵循 [Firebase 设置指南](https://firebase.google.com/docs/android/setup#manually_add_firebase)。
 - 您的 `Pushwoosh Application Code` 和来自您应用程序的 Pushwoosh 控制面板的 [Pushwoosh Device API Token](/zh/developer/api-reference/api-access-token/#device-api-token)。
</Aside>

## 集成步骤

### 1. 添加 Pushwoosh Capacitor SDK 依赖

将 Pushwoosh Capacitor SDK 依赖项添加到您的项目中：

```bash
npm install pushwoosh-capacitor-plugin
```

同步 Capacitor 配置：
```bash
npx cap sync
```

### 2. Capacitor SDK 初始化

在您的主 `JavaScript` 文件中，导入并初始化 Pushwoosh SDK：

```javascript title="index.js"
import { Pushwoosh } from 'pushwoosh-capacitor-plugin';

// Initialize the SDK
Pushwoosh.onDeviceReady({
    appid: "__YOUR_APP_CODE__"
});

// Register for push notifications
Pushwoosh.registerDevice()
    .then(result => {
        console.log("Push token:", result.pushToken);
        // Handle successful registration
    })
    .catch(error => {
        console.error("Failed to register device:", error);
        // Handle registration error
    });
```

其中：
- `__YOUR_APP_CODE__` 是来自 Pushwoosh 控制面板的应用程序代码。


### 3. iOS 原生设置

#### 3.1 功能

要在您的项目中启用推送通知，您需要添加某些功能。

在“签名与功能”部分，添加以下功能：
- `Push Notifications`
- `Background Modes`。添加此功能后，勾选 `Remote notifications` 复选框。

如果您打算使用时效性通知 (iOS 15+)，还需添加 `Time Sensitive Notifications` 功能。

#### 3.2 Info.plist

在您的 `Runner/Info.plist` 中，将 `__PUSHWOOSH_DEVICE_API_TOKEN__` 键设置为 [Pushwoosh Device API Token](/zh/developer/api-reference/api-access-token/#device-api-token)：
```xml title="info.plist"
<key>Pushwoosh_API_TOKEN</key>
<string>__PUSHWOOSH_DEVICE_API_TOKEN__</string>
```

#### 3.3 消息送达跟踪

您必须向您的项目添加一个通知服务扩展目标。这对于在 iOS 上实现准确的送达跟踪和富媒体等功能至关重要。

请遵循 [原生指南的步骤](/zh/developer/pushwoosh-sdk/ios-sdk/setting-up-pushwoosh-ios-sdk/basic-integration-guide/#4-message-delivery-tracking) 来添加扩展目标并在其中添加必要的 Pushwoosh 代码。

### 4. Android 原生设置

#### 4.1 安装依赖

确保所需的依赖项和插件已添加到您的 Gradle 脚本中：

将 Google Services Gradle 插件添加到您的项目级 `build.gradle` 依赖项中：

```groovy title="android/build.gradle"
buildscript {
  dependencies {
    classpath 'com.google.gms:google-services:4.3.15'
  }
}
```

在您的应用级 `build.gradle` 文件中应用该插件：

```groovy title="app/build.gradle"
apply plugin: 'com.google.gms.google-services'
```

#### 4.2 添加 Firebase 配置文件

将 `google-services.json` 文件放入您项目目录的 `android/app` 文件夹中。

#### 4.3 添加 Pushwoosh 元数据

在您的 `main/AndroidManifest.xml` 文件中，在 `<application>` 标签内添加 [Pushwoosh Device API Token](/zh/developer/api-reference/api-access-token/#device-api-token)：

```xml title="AndroidManifest.xml"
<meta-data android:name="com.pushwoosh.apitoken" android:value="__YOUR_DEVICE_API_TOKEN__" />
```

> **重要提示：** 请确保在您的 Pushwoosh 控制面板中为令牌授予对正确应用的访问权限。 [了解更多](/zh/developer/api-reference/api-access-token/#edit-token)

### 5. 运行项目

1. 构建并运行项目。
2. 转到 Pushwoosh 控制面板并 [发送一条推送通知](/zh/product/messaging-channels/push-notifications/send-push-notifications/one-time-push)。
3. 您应该会在应用中看到该通知。

## 扩展集成

至此，您已经集成了 SDK，可以发送和接收推送通知。现在，让我们来探索核心功能。

### 推送通知事件监听器

在 Pushwoosh Capacitor SDK 中，有两个用于处理推送通知的回调方法：

- `pushReceivedCallback` 在收到推送通知时触发
- `pushOpenedCallback` 在用户打开通知时触发

您应该在 SDK 初始化后立即设置这些回调：

```javascript title="index.js"
import { Pushwoosh } from 'pushwoosh-capacitor-plugin';

// Set up push received callback
await Pushwoosh.pushReceivedCallback((notification, err) => {
    if (err) {
        console.error("Failed to process received notification:", err);
    } else {
        console.log("Push received:", JSON.stringify(notification));
        // Handle the received notification
    }
});

// Set up push opened callback
await Pushwoosh.pushOpenedCallback((notification, err) => {
    if (err) {
        console.error("Failed to process opened notification:", err);
    } else {
        console.log("Push opened:", JSON.stringify(notification));
        // Handle the opened notification
    }
});
```

### 用户配置

通过关注个人用户的行为和偏好，您可以提供个性化内容，从而提高用户满意度和忠诚度。

```javascript
import { Pushwoosh } from 'pushwoosh-capacitor-plugin';

class Registration {
  async afterUserLogin(user) {

    // Set user ID
    Pushwoosh.setUserId(user.getId);
    
    // Setting additional user information as tags for Pushwoosh
    await Pushwoosh.setTags({
      "age": user.getAge(),
      "name": user.getName(),
      "last_login": user.getLastLoginDate()
    });
  }
}
```

### 标签 (Tags)

标签 (Tags) 是分配给用户或设备的键值对，允许根据偏好或行为等属性进行分段，从而实现有针对性的消息传递。

```javascript
import { Pushwoosh } from 'pushwoosh-capacitor-plugin';

class UpdateUser {
 async afterUserUpdateProfile(user) {

    // Set list of favorite categories
    await Pushwoosh.setTags({
      "favorite_categories": user.getFavoriteCategoriesList()
    });
    
    // Set payment information
    await Pushwoosh.setTags({
      "is_subscribed": user.isSubscribed(),
      "payment_status": user.getPaymentStatus(),
      "billing_address": user.getBillingAddress()
    });
  }
}
```

### 事件 (Events)

事件 (Events) 是应用内可以被跟踪的特定用户操作或发生的事情，用于分析行为并触发相应的消息或操作。

```javascript
import { Pushwoosh } from 'pushwoosh-capacitor-plugin';

class Registration {

  // Track login event
  afterUserLogin(user) {
    Pushwoosh.postEvent("login", {
      "name": user.getName(),
      "last_login": user.getLastLoginDate()
    });
  }

  // Track purchase event
  afterUserPurchase(product) {
    Pushwoosh.postEvent("purchase", {
      "product_id": product.getId(),
      "product_name": product.getName(),
      "price": product.getPrice(),
      "quantity": product.getQuantity()
    });
  }
}
```

## 故障排除

如果您在集成过程中遇到任何问题，请参阅 [支持和社区](/zh/developer/pushwoosh-sdk/support-and-community) 部分。