# Google Pay

了解如何用 Google Pay 收款。

有关各支付方式费用的信息，请参考[价格详情](https://stripe.com/pricing/local-payment-methods)。

借助 Google Pay，客户可以用他们在 Google 账户中存储的信用卡或借记卡在您的应用或网站上进行支付，包括 Google Play、YouTube、Chrome 或 Andriod 设备中绑定的银行卡。用 Google Pay API 请求您的客户在 Google 账户中存储的任何信用卡或借记卡。

Google Pay 与 Stripe 的产品和功能（例如，经常性付款）完全兼容，您可以随时在需要时用它替换传统的支付表单。用它来接收实物商品、捐赠、*订阅* (A Subscription represents the product details associated with the plan that your customer subscribes to. Allows you to charge the customer on a recurring basis)等的付款。

> #### Google Pay 条款
> 
> 集成 Google Pay，表示您同意 Google 的[服务条款](https://payments.developers.google.com/terms/sellertos)。

#### 支付方式属性

- **客户所在地**

  印度以外的全球

- **出示货币**

  参见[受支持的出示货币](https://docs.stripe.com/currencies.md#presentment-currencies)

- **支付确认**

  客户发起

- **支付方式类型**

  钱包

- **经常性付款**

  是

- **提现时间**

  适用标准提现时间

- **Connect 支持**

  是

- **争议支持**

  [是](https://docs.stripe.com/google-pay.md#disputed-payments)

- **手动捕获支持**

  是

- **退款/部分退款**

  [是 / 是](https://docs.stripe.com/google-pay.md#refunds)

#### 商家所在地

除印度外，全球的 Stripe 账户都可以用本国结算货币接受 Google Pay 付款。

#### 产品支持

- Connect
- Checkout
- Payment Links
- Elements
- Subscriptions
- Invoicing

## 使用 Stripe 和 Google Pay 与 Google Play 计费系统

本指南说明了如何配置您的应用以接受 Google Pay 支付实体商品、服务及其他符合条件的商品。Stripe 负责处理这些付款，您只需支付 Stripe 的 [处理费用](https://stripe.com/pricing)。

对于在美国或欧洲经济区 (EEA) 销售的数字化产品、内容和订阅，您的 Android 应用可以直接通过 Stripe 等第三方支付处理商在应用内收款。您可以使用以下支付界面：

- [移动版 Payment Element](https://docs.stripe.com/payments/mobile.md)，用于直接在应用内收款
- [Stripe Checkout](https://docs.stripe.com/mobile/digital-goods/checkout.md) 用于将客户重定向至 Stripe 托管的支付页面
- [Payment Links](https://docs.stripe.com/mobile/digital-goods/payment-links.md) 适用于数量有限的产品和价格

有关哪些购买必须使用 Google Play 计费系统的更多信息，请参见 Google Play 的[开发人员条款](https://support.google.com/googleplay/android-developer/answer/10281818)。

# React Native


Stripe 的 React Native SDK 是在您的 React Native 应用中开始接受 Google Pay 的最快最便捷的方式。[PlatformPayButton](https://stripe.dev/stripe-react-native/api-reference/index.html#PlatformPayButton) 组件包着 Google 要求的 UI，您可以通过最少的设置，用 `confirmPlatformPayPayment` 和 `createPlatformPayPaymentMethod` 方式在您的应用中无缝收取或创建付款。

> 如果您使用的是 React Native 和 Expo，则 Expo Go 不支持 Google Pay。要将 Expo 与 Google Pay 结合使用，您必须创建一个[开发版本](https://docs.expo.dev/get-started/set-up-your-environment/?mode=development-build&platform=android)。如果您已经有 Expo Go 项目，您可以[将其迁移到开发版本](https://docs.expo.dev/develop/development-builds/expo-go-to-dev-build/)。

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

### 服务器端

该集成要求您的服务器上的端点与 Stripe API 通讯。请用我们的官方库从您的服务器访问 Stripe API：

#### Ruby

```bash
# Available as a gem
sudo gem install stripe
```

```ruby
# If you use bundler, you can add this line to your Gemfile
gem 'stripe'
```

### 客户端

[React Native SDK](https://github.com/stripe/stripe-react-native) 是开源的，有完整的文档。在内部，它利用的是[原生 iOS](https://github.com/stripe/stripe-ios) 和 [Android](https://github.com/stripe/stripe-android) SDK。要安装 Stripe 的 React Native SDK，在您的项目目录中运行以下某个指令（取决于您使用的软件包管理器）。

#### yarn

```bash
yarn add @stripe/stripe-react-native
```

#### npm

```bash
npm install @stripe/stripe-react-native
```

然后，安装一些其他必要的依赖项：

- 对于 iOS，请前往 **ios** 目录并运行 `pod install`，以确保您也安装了所需的原生依赖项。
- 对于 Android，无需安装其他依赖项。

> 建议按照[官方 TypeScript 指南](https://reactnative.dev/docs/typescript#adding-typescript-to-an-existing-project)添加 TypeScript 支持。

### Stripe 初始化

要在您的 React Native 应用中初始化 Stripe，使用 `StripeProvider` 组件包裹您的支付界面，或者使用 `initStripe` 初始化方法。只需要 `publishableKey` 中的 API [公钥](https://docs.stripe.com/keys.md#obtain-api-keys)。下例显示的是用 `StripeProvider` 组件初始化 Stripe 的方式。

```jsx
import { useState, useEffect } from 'react';
import { StripeProvider } from '@stripe/stripe-react-native';

function App() {
  const [publishableKey, setPublishableKey] = useState('');

  const fetchPublishableKey = async () => {
    const key = await fetchKey(); // fetch key from your server here
    setPublishableKey(key);
  };

  useEffect(() => {
    fetchPublishableKey();
  }, []);

  return (
    <StripeProvider
      publishableKey={publishableKey}
      merchantIdentifier="merchant.identifier" // required for Apple Pay
      urlScheme="your-app" // required for 3D Secure and bank redirects
    >
      {/* Your app code here */}
    </StripeProvider>
  );
}
```

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

## 启用 Google Pay

要使用 Google Pay，先将以下内容添加到您的 **AndroidManifest.xml** 的 `<application>`标签，来启用 Google Pay API：

```xml
<application>
  ...
  <meta-data
    android:name="com.google.android.gms.wallet.api.enabled"
    android:value="true" />
</application>
```

更多详情，请参见 Google Pay 针对 Android 设备编写的[设置 Google Pay API](https://developers.google.com/pay/api/android/guides/setup) 指南。

## 创建 PaymentIntent [服务器端]

首先，在您的服务器上创建 `PaymentIntent`，并指定收款金额和币种：

```curl
curl https://api.stripe.com/v1/payment_intents \
  -u "<<YOUR_SECRET_KEY>>:" \
  -d amount=1099 \
  -d currency=usd
```

PaymentIntent 包含一个 *客户端私钥* (The client secret is a unique key returned from Stripe as part of a PaymentIntent. This key lets the client access important fields from the PaymentIntent (status, amount, currency) while hiding sensitive ones (metadata, customer))。您可以在 React Native 应用中使用该客户端私钥安全地完成支付流程，而无需传回整个 PaymentIntent 对象。在您的应用中，向服务器请求 PaymentIntent 并存储其客户端密钥。

## 初始化 Google Pay [客户端]

首先，通过调用 `isPlatformPaySupported` 查看设备是否支持 Google Pay。

```javascript
import { usePlatformPay } from '@stripe/stripe-react-native';

function PaymentScreen() {
  const { isPlatformPaySupported } = usePlatformPay();

  React.useEffect(() => {
    (async function () {
      if (!(await isPlatformPaySupported({ googlePay: {testEnv: true} }))) {
        Alert.alert('Google Pay is not supported.');
        return;
      }
    })();
  }, []);

  ...

  return (
    <View >
      ...
    </View>
  );
}
```

## 展示 Google Pay 表单 [客户端]

开通 Google Pay 并且您的应用程序获得了 `PaymentIntent` 或 `SetupIntent` 客户端私钥后，调用 `confirmPlatformPayPayment`。确认 `SetupIntent` 时，改为使用 `confirmPlatformPaySetupIntent`。

```javascript
import {PlatformPayButton, usePlatformPay} from '@stripe/stripe-react-native';

function PaymentScreen() {
  const {
    isPlatformPaySupported,
    confirmPlatformPayPayment,
  } = usePlatformPay();

  React.useEffect(() => {
    ... // see above
  }, []);

  const fetchPaymentIntentClientSecret = async () => {
    // Fetch payment intent created on the server, see above
    const response = await fetch(`${API_URL}/create-payment-intent`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        currency: 'usd',
      }),
    });
    const { clientSecret } = await response.json();

    return clientSecret;
  };

  const pay = async () => {
    const clientSecret = await fetchPaymentIntentClientSecret();

    const { error, paymentIntent } = await confirmPlatformPayPayment(
      clientSecret,
      {
        googlePay: {
          testEnv: true,
          merchantName: 'My merchant name',
          merchantCountryCode: 'US',
          currencyCode: 'USD',
          billingAddressConfig: {
            format: PlatformPay.BillingAddressFormat.Full,
            isPhoneNumberRequired: true,
            isRequired: true,
          },
        },
      }
    );

    if (error) {
      Alert.alert(error.code, error.message);
      // Update UI to prompt user to retry payment (and possibly another payment method)
      return;
    }
    Alert.alert('Success', 'The payment was confirmed successfully.');
    console.log(JSON.stringify(paymentIntent, null, 2));
  };

  return (
    <View >
      <PlatformPayButton
        type={PlatformPay.ButtonType.Pay}
        onPress={pay}
        style={{
          width: '100%',
          height: 50,
        }}
      />
    </View>
  );
}
```

## Optional: 创建 PaymentMethod [客户端]

如果您在您的服务器上确认付款，则可以用 Google Pay 仅收集 `PaymentMethod`，而非确认付款。要进行该调用，请使用 `createPlatformPayPaymentMethod` 方法：

```javascript
import {PlatformPayButton, usePlatformPay} from '@stripe/stripe-react-native';

function PaymentScreen() {
  const {
    isPlatformPaySupported,
    createPlatformPayPaymentMethod,
  } = usePlatformPay();

  React.useEffect(() => {
    ... // see above
  }, []);

  const createPaymentMethod = async () => {
    const { error, paymentMethod } = await createPlatformPayPaymentMethod({
      googlePay: {
        amount: 12,
        currencyCode: 'USD',
        testEnv: true,
        merchantName: 'Test',
        merchantCountryCode: 'US',
      },
    });

    if (error) {
      Alert.alert(error.code, error.message);
      return;
    } else if (paymentMethod) {
      Alert.alert(
        'Success',
        `The payment method was created successfully. paymentMethodId: ${paymentMethod.id}`
      );
    }
  };

  return (
    <View>
      <PlatformPayButton
        type={PlatformPay.ButtonType.GooglePayMark}
        onPress={createPaymentMethod}
        style={{
          width: '100%',
          height: 50,
        }}
      />
    </View>
  );
}
```

## Google Pay 上线

按照 [Google 的说明](https://developers.google.com/pay/api/android/guides/test-and-deploy/request-prod-access)，请求访问您的应用程序的生产环境。收到提示时，选择集成类型 **Gateway**，并提供您的应用的截图供审核。

应用获批准后，使用 `testEnv: false`，并从经过签名的应用正式发布版本中启动 Google Pay，以在生产环境中测试您的集成。请记得使用您的*真实模式* (Use this mode when you’re ready to launch your app. Card networks or payment providers process payments) [API 密钥](https://docs.stripe.com/keys.md)。您可以使用带有 [capture_method=manual](https://docs.stripe.com/api/payment_intents/create.md#create_payment_intent-capture_method) 的 `PaymentIntent` 来处理交易，而无需捕获付款。

### 测试 Google Pay

Google 允许您通过其[测试卡套件](https://developers.google.com/pay/api/android/guides/resources/test-card-suite)进行测试付款。该测试套件支持使用 Stripe [测试卡](https://docs.stripe.com/testing.md)。

您必须在支持 Google Pay 的国家/地区使用 Android 实体设备（而不是模拟设备）测试 Google Pay。使用保存到 Google 钱包的真实银行卡登录测试设备上的 Google 账户。


## 争议

用户必须验证用他们的 Google Pay 账户进行的付款，以降低发生欺诈或付款无法识别的风险。但是，用户仍然可以在完成付款后对交易提出争议。您可以直接提交证据，对争议提出质疑。争议流程与银行卡付款相同。了解如何[管理争议](https://docs.stripe.com/disputes/responding.md)。

### Google Pay 收款的责任转移

Google Pay 在全球范围内支持[责任转移](https://docs.stripe.com/payments/3d-secure/authentication-flow.md#disputed-payments)。这自动适用于使用 Stripe 托管产品和 Stripe.js 的用户。对于 Stripe 托管产品以外的 Visa 交易，您必须在 Google Pay & Wallet 控制台中启用责任转移。为此，请访问您的 ***Google Pay & Wallet 控制台***，在左侧导航栏中选择 ***Google Pay API***，然后启用 ***Visa 设备令牌欺诈责任保护***，以提供责任转移保护。

Google Pay 交易可在三种场景中使用：

1. 如果用户用其移动设备向 Google Pay 应用添加银行卡，则该卡会作为一个设备主账号 (DPAN) 进行保存，并且默认支持责任转移。
2. 如果用户向 Chrome 或 Google 的一个属性（例如，YouTube 或 Play）添加银行卡，那么该银行卡会作为充值主账号 (FPAN) 进行保存。当您使用 [3DS 验证](https://docs.stripe.com/payments/3d-secure.md)时，我们全球支持所有主要卡组织的责任转移，包括 Visa。您可以自定义 [Stripe Radar 规则](https://docs.stripe.com/radar/rules.md#request-3d-secure)来请求激活 3DS 验证。
3. 如果用户在用 Google Pay 支付的电商网站或应用中选择 Google Pay 作为支付方式，则这些卡将以电商令牌的形式保存，在文件中表示这些卡。目前电商令牌不支持责任转移和 3DS 验证。

对于 Sigma 用户，`charges` 表包含一个指示 Google Pay 交易类型的 `card_token_type` 字段。FPAN 交易将 `card_token_type` 设置为 `fpan`。DPAN 和电商令牌交易将 `card_token_type` 设置为 `dpan_or_ecommerce_token`。

## 退款

您可以部分或全额退还任何成功的 Google Pay 付款。退款流程与银行卡付款相同。有关发起或管理退款的说明，请参阅[退款和取消付款](https://docs.stripe.com/refunds.md)。
