Zum Inhalt springen

Google Pay

Google Pay bestätigt einen PaymentIntent in einer einzigen Darstellung. Die Android-Implementierung akzeptiert zusätzlich einen SetupIntent, die Web-Implementierung nicht.

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

Im Web verwendet Google Pay den Payment Request Button. Stellen Sie die Anwendung in Entwicklung und Produktion über HTTPS bereit.

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

Plattformunterstützung

Plattform Google Pay
Android Nativer GooglePayLauncher (benötigt Anwendungsmetadaten)
iOS Nicht implementiert
Web Payment Request Button (stripe-pwa-elements)

iOS weist isGooglePayAvailable, createGooglePay und presentGooglePay zurück. Android liest die Google-Pay-Konfiguration beim Laden des Plugins aus Metadaten. initialize allein reicht unter Android deshalb nicht aus.

Einstellungen vorbereiten

strings.xml

Ergänzen Sie in android/app/src/main/res/values/strings.xml:

  • publishable_key (veröffentlichbarer Stripe-Schlüssel)
  • 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>

Optionales Stripe Connect für Android-Google-Pay:

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

AndroidManifest.xml

Ergänzen Sie in android/app/src/main/AndroidManifest.xml unter manifest > application Folgendes:

<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"/>

Optionales verbundenes Konto:

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

Optional 1: Setzen Sie zum Abrufen von Nutzerinformationen Folgendes:

<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"/>

Optional 2: Wenn Sie keine vorhandene Zahlungsmethode in Google Pay verlangen:

Bei false gilt Google Pay auch dann als bereit, wenn die Google-Pay-Wallet des Kunden keine vorhandenen Zahlungsmethoden enthält. Der Standard ist 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

Das Promise wird aufgelöst, wenn Google Pay bereit ist, andernfalls zurückgewiesen.

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

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

method isGooglePayAvailable()

Wird aufgelöst, wenn Google Pay verfügbar ist, und andernfalls abgelehnt.
Google Pay wird auf Android und in kompatiblen Webbrowsern unterstützt, nicht auf iOS.

isGooglePayAvailable() => Promise<void>

2. createGooglePay

Rufen Sie ein PaymentIntent-Client-Secret von Ihrem Backend ab. Unter Android können Sie stattdessen ein SetupIntent-Client-Secret übergeben. Ersetzen Sie /your-intent-endpoint im Beispiel durch die Backend-URL aus Serverintegration. Die Option heißt für beide Intent-Typen paymentIntentClientSecret. Im Web sind außerdem paymentSummaryItems, merchantIdentifier, countryCode und currency erforderlich.

// `/your-intent-endpoint` durch Ihr Backend aus der Anleitung zur Serverintegration ersetzen.
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;
};

await Stripe.createGooglePay({
  paymentIntentClientSecret: paymentIntent,

  // Nur im Web. Google Pay in einer Android-App benötigt dies nicht
  paymentSummaryItems: [{
    label: 'Product Name',
    amount: 1099.00
  }],
  merchantIdentifier: 'merchant.com.getcapacitor.stripe',
  countryCode: 'US',
  currency: 'USD',
});

method createGooglePay(...)

Erstellt eine Google-Pay-Anfrage. Vor presentGooglePay() aufrufen.

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

interface CreateGooglePayOption

Eigenschaft Typ Beschreibung Seit
paymentIntentClientSecret string Client Secret des mit Google Pay zu bestätigenden PaymentIntent. 3.2.0
paymentSummaryItems { label: string; amount: number; }[] Nur Web. Erfordert stripe-pwa-elements ^3.0.0. 3.2.0
merchantIdentifier string Nur Web. Erfordert stripe-pwa-elements ^3.0.0. 3.2.0
countryCode string Nur Web. Erfordert stripe-pwa-elements ^3.0.0. 3.2.0
currency string Nur Web. Erfordert stripe-pwa-elements ^3.0.0. 3.2.0

Ein SetupIntent-Client-Secret beginnt mit seti_. Android erkennt dieses Präfix und verwendet presentForSetupIntent mit currency aus den Erstellungsoptionen, standardmäßig USD. Übergeben Sie im Web keinen SetupIntent: Die Web-Implementierung bestätigt mit confirmCardPayment.

3. presentGooglePay

const result = await Stripe.presentGooglePay();
if (result.paymentResult === GooglePayEventsEnum.Completed) {
  // Nur die UI aktualisieren. Den Intent vor der Leistungserbringung per Webhook bestätigen.
}

method presentGooglePay()

Zeigt die mit createGooglePay() erstellte Google-Pay-Anfrage an.

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

type alias GooglePayResultInterface

GooglePayEventsEnum.Completed | GooglePayEventsEnum.Canceled | GooglePayEventsEnum.Failed

Behandeln Sie Canceled als Abbruch und Failed als Fehler. Bevorzugen Sie nach der Neuerstellung einer Android-Activity Ergebnis-Listener. Siehe Ereignis-Listener.

4. addListener

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

enum GooglePayEventsEnum

Mitglied Wert
Loaded 'googlePayLoaded'
FailedToLoad 'googlePayFailedToLoad'
Completed 'googlePayCompleted'
Canceled 'googlePayCanceled'
Failed 'googlePayFailed'

Referenz

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: 1099.00
    }],
    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.
  }
})();