Google Pay
Google Pay confirme un PaymentIntent en une seule présentation. L’implémentation Android accepte également un SetupIntent ; l’implémentation Web ne l’accepte pas.
https://stripe.com/docs/google-pay
Sur le Web, Google Pay utilise le Payment Request Button. Servez l’application en HTTPS en développement comme en production.
Prise en charge des plateformes
| Plateforme | Google Pay |
|---|---|
| Android | GooglePayLauncher natif (nécessite les métadonnées de l’application) |
| iOS | Non implémenté |
| Web | Payment Request Button (stripe-pwa-elements) |
iOS rejette isGooglePayAvailable, createGooglePay et presentGooglePay. Android lit la configuration Google Pay dans les métadonnées lors du chargement du plugin ; initialize seul ne suffit donc pas sur Android.
Préparer les paramètres
strings.xml
Dans android/app/src/main/res/values/strings.xml, ajoutez :
publishable_key(clé publique Stripe)enable_google_paycountry_codemerchant_display_namegoogle_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 facultatif pour Google Pay sur Android :
<string name="stripe_account">acct_xxxxxxxxxxxxx</string>
AndroidManifest.xml
Dans android/app/src/main/AndroidManifest.xml, ajoutez les éléments suivants sous 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"/>
Compte connecté facultatif :
<meta-data
android:name="com.getcapacitor.community.stripe.stripe_account"
android:value="@string/stripe_account"/>
Option 1 : pour obtenir les informations utilisateur, définissez ces paramètres :
<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"/>
Option 2 : si vous n’exigez pas de moyen de paiement existant dans Google Pay :
Si ce paramètre est false, Google Pay est considéré comme prêt même si le portefeuille Google Pay du client ne contient pas de moyen de paiement existant. La valeur par défaut est 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 Promise est résolue lorsque Google Pay est prêt et rejetée sinon.
import { GooglePayEventsEnum, Stripe } from '@capacitor-community/stripe';
try {
await Stripe.isGooglePayAvailable();
} catch {
return;
}
method isGooglePayAvailable()
Se résout lorsque Google Pay est disponible et est rejeté lorsqu’il ne l’est pas.
Google Pay est pris en charge sur Android et les navigateurs Web compatibles, mais pas sur iOS.
isGooglePayAvailable() => Promise<void>
2. createGooglePay
Récupérez un secret client de PaymentIntent depuis votre backend. Sur Android, vous pouvez passer à la place un secret client de SetupIntent. Remplacez /your-intent-endpoint dans l’exemple par l’URL du backend présentée dans Intégration serveur. L’option s’appelle paymentIntentClientSecret pour les deux types d’Intent. Le Web nécessite également paymentSummaryItems, merchantIdentifier, countryCode et currency.
// Remplacez `/your-intent-endpoint` par votre backend décrit dans Intégration serveur.
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,
// Web uniquement. Google Pay dans une application Android ne le nécessite pas.
paymentSummaryItems: [{
label: 'Product Name',
amount: 1099.00
}],
merchantIdentifier: 'merchant.com.getcapacitor.stripe',
countryCode: 'US',
currency: 'USD',
});
method createGooglePay(...)
Crée une demande Google Pay. Appelez cette méthode avant presentGooglePay().
createGooglePay(options: CreateGooglePayOption) => Promise<void>
interface CreateGooglePayOption
| Propriété | Type | Description | Depuis |
|---|---|---|---|
paymentIntentClientSecret |
string |
Secret client du PaymentIntent à confirmer avec Google Pay. | 3.2.0 |
paymentSummaryItems |
{ label: string; amount: number; }[] |
Web uniquement. Nécessite stripe-pwa-elements ^3.0.0. | 3.2.0 |
merchantIdentifier |
string |
Web uniquement. Nécessite stripe-pwa-elements ^3.0.0. | 3.2.0 |
countryCode |
string |
Web uniquement. Nécessite stripe-pwa-elements ^3.0.0. | 3.2.0 |
currency |
string |
Web uniquement. Nécessite stripe-pwa-elements ^3.0.0. | 3.2.0 |
Un secret client de SetupIntent commence par seti_. Android détecte ce préfixe et utilise presentForSetupIntent avec la currency des options de création (USD par défaut). Ne passez pas de SetupIntent sur le Web : l’implémentation Web confirme avec confirmCardPayment.
3. presentGooglePay
const result = await Stripe.presentGooglePay();
if (result.paymentResult === GooglePayEventsEnum.Completed) {
// Mettez uniquement l’interface à jour. Confirmez l’Intent par webhook avant d’exécuter la commande.
}
method presentGooglePay()
Présente la demande Google Pay créée par createGooglePay().
presentGooglePay() => Promise<{ paymentResult: GooglePayResultInterface; }>
type alias GooglePayResultInterface
GooglePayEventsEnum.Completed | GooglePayEventsEnum.Canceled | GooglePayEventsEnum.Failed
Traitez Canceled comme une annulation et Failed comme une erreur. Préférez les écouteurs de résultat après une recréation de l’Activity Android. Consultez Écouteurs d’événements.
4. addListener
Stripe.addListener(GooglePayEventsEnum.Completed, () => {
console.log('GooglePayEventsEnum.Completed');
});
enum GooglePayEventsEnum
| Membre | Valeur |
|---|---|
Loaded |
'googlePayLoaded' |
FailedToLoad |
'googlePayFailedToLoad' |
Completed |
'googlePayCompleted' |
Canceled |
'googlePayCanceled' |
Failed |
'googlePayFailed' |
Référence
<?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>
<?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>
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.
}
})();