Saltar al contenido

Google Pay

Google Pay confirma un PaymentIntent en una sola presentación. La implementación en Android también acepta un SetupIntent; en cambio, la implementación en la web no lo hace.

https://stripe.com/docs/google-payhttps://stripe.com/docs/google-pay

En la web, Google Pay utiliza el botón “Solicitar Pago”. La aplicación se ejecuta mediante HTTPS, tanto en la fase de desarrollo como en la producción.

https://stripe.com/docs/stripe-js/elements/payment-request-button?platform=html-js-testing-google-pay#html-js-prerequisiteshttps://stripe.com/docs/stripe-js/elements/payment-request-button?platform=html-js-testing-google-pay#html-js-prerequisites

Plataformas compatibles

Plataforma Google Pay
Android GooglePayLauncher nativo (requiere los metadatos de la aplicación)
iOS Sin implementar
Web Payment Request Button (stripe-pwa-elements)

iOS rechaza isGooglePayAvailable, createGooglePay y presentGooglePay. Android lee la configuración de Google Pay de los metadatos al cargar el plugin, por lo que en Android no basta con llamar a initialize.

Prepara la configuración

strings.xml

En android/app/src/main/res/values/strings.xml, añade:

  • publishable_key (clave publicable de Stripe)
  • enable_google_pay
  • country_code
  • merchant_display_name
  • google_pay_is_testing
<string name="publishable_key">Your Publishable Key</string>
<bool name="enable_google_pay">true</bool>
<string name="country_code">US</string>
<string name="merchant_display_name">Widget Store</string>
<bool name="google_pay_is_testing">true</bool>

Stripe Connect opcional en Google Pay para Android:

<string name="stripe_account">acct_xxxxxxxxxxxxx</string>

AndroidManifest.xml

En android/app/src/main/AndroidManifest.xml, añade lo siguiente dentro de manifest > application:

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

<meta-data
  android:name="com.getcapacitor.community.stripe.enable_google_pay"
  android:value="@bool/enable_google_pay"/>

<meta-data
  android:name="com.getcapacitor.community.stripe.publishable_key"
  android:value="@string/publishable_key"/>

<meta-data
  android:name="com.getcapacitor.community.stripe.country_code"
  android:value="@string/country_code"/>

<meta-data
  android:name="com.getcapacitor.community.stripe.merchant_display_name"
  android:value="@string/merchant_display_name"/>

<meta-data
  android:name="com.getcapacitor.community.stripe.google_pay_is_testing"
  android:value="@bool/google_pay_is_testing"/>

Cuenta conectada opcional:

<meta-data
  android:name="com.getcapacitor.community.stripe.stripe_account"
  android:value="@string/stripe_account"/>

Opcional: configura estos valores si solicitas datos del usuario

<bool name="email_address_required">true</bool>
<bool name="phone_number_required">true</bool>
<bool name="billing_address_required">true</bool>
<string name="billing_address_format">Full</string>
<meta-data
  android:name="com.getcapacitor.community.stripe.email_address_required"
  android:value="@bool/email_address_required"/>

<meta-data
  android:name="com.getcapacitor.community.stripe.phone_number_required"
  android:value="@bool/phone_number_required"/>

<meta-data
  android:name="com.getcapacitor.community.stripe.billing_address_required"
  android:value="@bool/billing_address_required"/>

<meta-data
  android:name="com.getcapacitor.community.stripe.billing_address_format"
  android:value="@string/billing_address_format"/>

Opcional: si Google Pay puede utilizarse sin un método de pago guardado

Si se establece en false, Google Pay se considera disponible aunque el cliente aún no tenga métodos de pago en su cartera de Google Pay. El valor predeterminado es true.

<bool name="google_pay_existing_payment_method_required">false</bool>
<meta-data
  android:name="com.getcapacitor.community.stripe.google_pay_existing_payment_method_required"
  android:value="@bool/google_pay_existing_payment_method_required"/>

1. isGooglePayAvailable

La promesa se resuelve cuando Google Pay está listo. En caso contrario, se rechaza.

import { GooglePayEventsEnum, Stripe } from '@capacitor-community/stripe';

try {
  await Stripe.isGooglePayAvailable();
} catch {
  return;
}

method isGooglePayAvailable()

La promesa se resuelve si Google Pay está disponible y se rechaza en caso contrario. Google Pay funciona en Android y en navegadores compatibles, pero no en iOS.

isGooglePayAvailable() => Promise<void>

2. createGooglePay

paymentSummaryItems.amount usa la unidad principal de la moneda: 10.99 equivale a 10,99 USD. En cambio, el importe del PaymentIntent de Stripe en el servidor se expresa en la unidad mínima (1099 para ese mismo importe en USD). El total mostrado debe corresponder al importe del Intent en el servidor.

Obtén un secreto de cliente de PaymentIntent de tu servidor. En Android también puedes usar el de un SetupIntent. Consulta Integración con el servidor. La opción se llama paymentIntentClientSecret para ambos tipos de Intent. La web requiere además paymentSummaryItems, merchantIdentifier, countryCode y currency.

import { firstValueFrom } from 'rxjs';

const { paymentIntent } = await firstValueFrom(
  this.http.post<{
    paymentIntent: string;
  }>(environment.api + 'intent', {}),
);

await Stripe.createGooglePay({
  paymentIntentClientSecret: paymentIntent,

  // Solo para la web. Google Pay no lo necesita en una aplicación Android.
  paymentSummaryItems: [
    {
      label: 'Product Name',
      amount: 10.99,
    },
  ],
  merchantIdentifier: 'merchant.com.getcapacitor.stripe',
  countryCode: 'US',
  currency: 'USD',
});

method createGooglePay(...)

Crea una solicitud de Google Pay. Llama a este método antes de presentGooglePay().

createGooglePay(options: CreateGooglePayOption) => Promise<void>

interface CreateGooglePayOption

Propiedad Tipo Descripción Desde la versión
paymentIntentClientSecret string Secreto de cliente del PaymentIntent que se confirmará con Google Pay. 3.2.0
paymentSummaryItems { label: string; amount: number; }[] Solo para la web. Requiere stripe-pwa-elements ^5.3.0. 3.2.0
merchantIdentifier string Solo para la web. Requiere stripe-pwa-elements ^5.3.0. 3.2.0
countryCode string Solo para la web. Requiere stripe-pwa-elements ^5.3.0. 3.2.0
currency string Solo para la web. Requiere stripe-pwa-elements ^5.3.0. 3.2.0

El secreto de cliente de un SetupIntent empieza con seti_. Android detecta ese prefijo y usa presentForSetupIntent con la opción currency de la creación (valor predeterminado: USD). No pases SetupIntent en la web: la implementación web confirma el pago con confirmCardPayment.

3. presentGooglePay

const result = await Stripe.presentGooglePay();
if (result.paymentResult === GooglePayEventsEnum.Completed) {
  // Actualiza solo la interfaz. Antes de entregar el pedido, verifica el pago en el servidor mediante webhooks.
}

method presentGooglePay()

Muestra la solicitud de Google Pay creada por createGooglePay().

presentGooglePay() => Promise<{ paymentResult: GooglePayResultInterface; }>

type alias GooglePayResultInterface

GooglePayEventsEnum.Completed | GooglePayEventsEnum.Canceled | GooglePayEventsEnum.Failed

Trata Canceled como una cancelación y Failed como un error. Si Android vuelve a crear la Activity, da preferencia a los listeners de resultados. Consulta Listeners de eventos.

4. addListener

Stripe.addListener(GooglePayEventsEnum.Completed, () => {
  console.log('GooglePayEventsEnum.Completed');
});

enum GooglePayEventsEnum

Miembro Valor
Loaded 'googlePayLoaded'
FailedToLoad 'googlePayFailedToLoad'
Completed 'googlePayCompleted'
Canceled 'googlePayCanceled'
Failed 'googlePayFailed'

Referencia

strings.xml
<?xml version='1.0' encoding='utf-8'?>
<resources>
    <string name="app_name">capacitor-stripe</string>
    <string name="title_activity_main">capacitor-stripe</string>
    <string name="package_name">io.ionic.starter</string>
    <string name="custom_url_scheme">io.ionic.starter</string>

    <string name="publishable_key">Your Publishable Key</string>
    <bool name="enable_google_pay">true</bool>
    <string name="country_code">US</string>
    <string name="merchant_display_name">Widget Store</string>
    <bool name="google_pay_is_testing">true</bool>

    <bool name="email_address_required">true</bool>
    <bool name="phone_number_required">true</bool>
    <bool name="billing_address_required">true</bool>
    <string name="billing_address_format">Full</string>

    <bool name="google_pay_existing_payment_method_required">false</bool>
</resources>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="io.ionic.starter">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
            android:name="io.ionic.starter.MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBarLaunch"
            android:launchMode="singleTask">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>

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

        <meta-data
          android:name="com.getcapacitor.community.stripe.enable_google_pay"
          android:value="@bool/enable_google_pay"/>

        <meta-data
          android:name="com.getcapacitor.community.stripe.publishable_key"
          android:value="@string/publishable_key"/>

        <meta-data
          android:name="com.getcapacitor.community.stripe.country_code"
          android:value="@string/country_code"/>

        <meta-data
          android:name="com.getcapacitor.community.stripe.merchant_display_name"
          android:value="@string/merchant_display_name"/>

        <meta-data
          android:name="com.getcapacitor.community.stripe.google_pay_is_testing"
          android:value="@bool/google_pay_is_testing"/>

        <meta-data
          android:name="com.getcapacitor.community.stripe.email_address_required"
          android:value="@bool/email_address_required"/>

        <meta-data
          android:name="com.getcapacitor.community.stripe.phone_number_required"
          android:value="@bool/phone_number_required"/>

        <meta-data
          android:name="com.getcapacitor.community.stripe.billing_address_required"
          android:value="@bool/billing_address_required"/>

        <meta-data
          android:name="com.getcapacitor.community.stripe.billing_address_format"
          android:value="@string/billing_address_format"/>

        <meta-data
          android:name="com.getcapacitor.community.stripe.google_pay_existing_payment_method_required"
          android:value="@bool/google_pay_existing_payment_method_required"/>
    </application>

    <!-- Permissions -->

    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

google-pay.ts
import { GooglePayEventsEnum, Stripe } from '@capacitor-community/stripe';

(async () => {
  try {
    await Stripe.isGooglePayAvailable();
  } catch {
    return;
  }

  await Stripe.addListener(GooglePayEventsEnum.Completed, () => {
    console.log('GooglePayEventsEnum.Completed');
  });

  // Replace `/your-intent-endpoint` with your backend from Server Integration.
  const response = await fetch('/your-intent-endpoint', {
    method: 'POST',
  });
  if (!response.ok) {
    throw new Error(`Intent request failed: ${response.status}`);
  }
  const { paymentIntent } = (await response.json()) as {
    paymentIntent: string;
  };

  // Prepare Google Pay
  await Stripe.createGooglePay({
    paymentIntentClientSecret: paymentIntent,

    // Web only. Google Pay on Android App doesn't need
    paymentSummaryItems: [{
      label: 'Product Name',
      amount: 10.99
    }],
    merchantIdentifier: 'merchant.com.getcapacitor.stripe',
    countryCode: 'US',
    currency: 'USD',
  });

  // Present Google Pay
  const result = await Stripe.presentGooglePay();
  if (result.paymentResult === GooglePayEventsEnum.Completed) {
    // Update UI only. Fulfill orders from a verified server webhook.
  }
})();