# 收集物理地址和电话号码

了解如何使用 Address Element 在移动端应用中收集客户地址和电话号码。

# Android


要收集完整的地址以进行计费或送货，请使用 [Address Element](https://docs.stripe.com/payments/mobile/address-element.md)。

还可以使用 Address Element 执行以下作：

- 收集客户[电话号码](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet.addresselement/-address-launcher/-additional-fields-configuration/index.html)
- 使用自动完成功能（默认启用）
- 通过传入收货地址在 Payment Element 中预填充账单信息

Stripe 将收集的地址信息和支付方式合在一起来创建 *PaymentIntent* (API object that represents your intent to collect payment from a customer, tracking charge attempts and payment state changes throughout the process)。
![用户选择“添加收货地址”选项的结账流程示例。然后，他们被带到一个新的界面，将他们的收货地址添加到一个表单中（他们会在键入地址时看到自动完成建议）。](https://b.stripecdn.com/docs-statics-srv/assets/android-overview.414fc754c90afc0ec42840299c12022d.png)

## 设置 Stripe [服务器端] [客户端]

首先，您需要有 Stripe 账户。[立即注册](https://dashboard.stripe.com/register)。

[Stripe Android SDK](https://github.com/stripe/stripe-android) 是开源的，且[有完整的文档](https://stripe.dev/stripe-android/)。

安装 SDK 时，将 `stripe-android` 添加到您的 [app/build.gradle](https://developer.android.com/studio/build/dependencies) 文件的 `dependencies` 块中：

#### Kotlin

```kotlin
plugins {
    id("com.android.application")
}

android { ... }

dependencies {
  // ...

  // Stripe Android SDK
  implementation("com.stripe:stripe-android:24.0.0")
  // Include the financial connections SDK to support US bank account as a payment method
  implementation("com.stripe:financial-connections:24.0.0")
}
```

> 有关最新 SDK 发布及过往版本的详细信息，请查看 GitHub 上的[发布](https://github.com/stripe/stripe-android/releases)页面。要想在新版本发布时接收通知，请[查看仓库的发布情况](https://docs.github.com/en/github/managing-subscriptions-and-notifications-on-github/configuring-notifications#configuring-your-watch-settings-for-an-individual-repository)。

用您的 Stripe [公钥](https://dashboard.stripe.com/apikeys)配置 SDK，以便它可以向 Stripe API 发送请求，例如在您的 `Application` 子类中：

#### Kotlin

```kotlin
import com.stripe.android.PaymentConfiguration

class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        PaymentConfiguration.init(
            applicationContext,
            "<<YOUR_PUBLISHABLE_KEY>>"
        )
    }
}
```

> 测试时使用您的[测试密钥](https://docs.stripe.com/keys.md#obtain-api-keys)，发布应用时使用[真实模式](https://docs.stripe.com/keys.md#test-live-modes)密钥。

## 设置地址自动完成建议

当您的客户选择受支持的国家/地区时，Stripe 会自动提供自动完成建议。无需额外的集成步骤。

> 使用自动完成功能即表示您同意遵守 [Google Maps 平台可接受的使用政策](https://cloud.google.com/maps-platform/terms/aup)。如果您违反该政策，Stripe 可能会停用自动完成功能，或采取其他必要措施。

## 配置 Address Element

可以使用显示默认值、设置允许的国家/地区、自定义外观等详细信息来配置 Address Element。有关配置选项的完整列表，请参阅 [AddressLauncher.Configuration](https://github.com/stripe/stripe-android/blob/master/paymentsheet/src/main/java/com/stripe/android/paymentsheet/addresselement/AddressLauncher.kt#L72)。

```kotlin
val addressConfiguration = AddressLauncher.Configuration.Builder()
    .additionalFields(
        AddressLauncher.AdditionalFieldsConfiguration(
            phone = AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration.REQUIRED
        )
    )
    .allowedCountries(setOf("US", "CA", "GB"))
    .title("Shipping Address")
    .build()
```

Address Element 最初会显示一个单一的地址输入框。客户输入地址时，系统会在输入框内显示匹配的地址建议。当客户选择某个建议后，Address Element 会自动填充地址表单。

## 检索地址详情

通过在 `Activity` 或 `Fragment` 的 `onCreate` 生命周期方法中创建 `AddressLauncher` 实例，并创建实现 `AddressLauncherResultCallback` 接口的回调方法来检索地址详细信息。

```kotlin
private lateinit var addressLauncher: AddressLauncher
private var shippingDetails: AddressDetails? = null

override fun onCreate(savedInstanceState: Bundle?) {
    addressLauncher = AddressLauncher(this, ::onAddressLauncherResult)
}

private fun onAddressLauncherResult(result: AddressLauncherResult) {
    // TODO: Handle result and update your UI
    when (result) {
        is AddressLauncherResult.Succeeded -> {
            shippingDetails = result.address
        }
        is AddressLauncherResult.Canceled -> {
            // TODO: Handle cancel
        }
    }
}
```

`AddressLauncherResult` 可以是 `Succeeded` 或 `Canceled`。请参阅更多[实现细节](https://github.com/stripe/stripe-android/blob/master/paymentsheet/src/main/java/com/stripe/android/paymentsheet/addresselement/AddressLauncherResult.kt)。

> Stripe 要求您在 `onCreate` 生命周期事件期间（而不是之后）实例化 `AddressLauncher`。否则，回调无法正确注册，您的应用将崩溃。

## 显示 Address Element

使用地址启动器和先前步骤中的配置来展示 Address Element。

```kotlin
addressLauncher.present(
   publishableKey = publishableKey,
   configuration = addressConfiguration
)
```

## Optional: 在 Payment Element 中预填充收货地址

如果使用移动端 Payment Element，请将[PaymentSheet.Configuration.shippingDetails](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet/-payment-sheet/-configuration/index.html) 设置为地址元素收集的地址。当 `shippingDetails` 被填入时，用户的账单地址会被预填，他们会看到一个**账单地址与收货地址相同**的复选框。当确认 PaymentIntent 时，已填充 `shippingDetails` 的已确认 PaymentIntents 也会填充 [shipping](https://docs.stripe.com/api/payment_intents/object.md#payment_intent_object-shipping) intent 属性

```kotlin
val configuration = PaymentSheet.Configuration.Builder("Example, Inc.")
  // ...
  .shippingDetails(shippingDetails)
  .build()
```

## Optional: 自定义外观

现在，您已将 Address Element 添加到您的应用程序中，您可以自定义其外观，以匹配应用其余部分的设计。您可以使用 [Appearance API](https://docs.stripe.com/elements/appearance-api/mobile.md?platform=android) 通过 [AddressLauncher.Configuration.appearance](https://stripe.dev/stripe-android/paymentsheet/com.stripe.android.paymentsheet.addresselement/-address-launcher/-configuration/index.html) 来配置外观。

## Optional: 设置默认账单详情

要为支付表单中收集的账单详情设置默认值，请配置 `defaultBillingDetails` 属性。`paymentSheet` 会用您提供的值预先填充其字段。

#### Kotlin

```kotlin
val address = PaymentSheet.Address(country = "US")
val billingDetails = PaymentSheet.BillingDetails(
  address = address,
  email = "foo@bar.com"
)
val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "Merchant, Inc.")
  .defaultBillingDetails(billingDetails)
  .build()
```

## Optional: 自定义账单地址信息的收集

### 配置账单详情的收集

使用 `BillingDetailsCollectionConfiguration` 指定您希望在 PaymentSheet 中收集账单详情的方式。

可以收集客户的姓名、邮件地址、电话号码和地址。

完整的地址收集功能包含 Stripe 针对受支持国家/地区提供的自动完成功能，无需额外设置。

> 使用自动完成功能即表示您同意遵守 [Google Maps 平台可接受的使用政策](https://cloud.google.com/maps-platform/terms/aup)。如果您违反该政策，Stripe 可能会停用自动完成功能，或采取其他必要措施。

如果希望将默认账单详情关联到 PaymentMethod 对象（即使 UI 中未收集这些字段），请将 `billingDetailsCollectionConfiguration.attachDefaultsToPaymentMethod` 设置为 `true`。

#### Kotlin

```kotlin
val billingDetails = PaymentSheet.BillingDetails(
  email = "foo@bar.com"
)
val billingDetailsCollectionConfiguration = BillingDetailsCollectionConfiguration(
  attachDefaultsToPaymentMethod = true,
  name = BillingDetailsCollectionConfiguration.CollectionMode.Always,
  email = BillingDetailsCollectionConfiguration.CollectionMode.Never,
  address = BillingDetailsCollectionConfiguration.AddressCollectionMode.Full,
)
val configuration = PaymentSheet.Configuration.Builder(merchantDisplayName = "Merchant, Inc.")
  .defaultBillingDetails(billingDetails)
  .billingDetailsCollectionConfiguration(billingDetailsCollectionConfiguration)
  .build()
```

> 请咨询律师，了解与收集信息有关的法律。仅在需要收集号码来完成交易时，才收集手机号码。

## Optional: 自定义自动补全国家/地区

默认情况下，自动补全建议适用于所有 Stripe 支持的国家/地区。如需将自动补全功能限制在特定国家/地区，请通过 `autocompleteCountries` 参数提供这些国家/地区的两个字母国家/地区代码:

```kotlin
val addressConfiguration = AddressLauncher.Configuration.Builder()
    .autocompleteCountries(setOf("US", "CA", "GB"))
    .build()
```

此设置仅控制自动补全建议显示的位置，并不会限制客户在地址表单中可以选择的国家/地区。如需限制国家/地区选择，请使用 `allowedCountries`。当自动补全功能不可用时，客户可以手动输入地址。

