'Flutter In-App Purchase Implement For Google Pay
I am trying to update my existing application on google play store from Android Java with Flutter Dart. On my existing application, I have an in-app purchase that uses google pay which works perfectly (With android java coding) but I am looking for how to implement google pay in-app purchase with flutter dart.
Solution 1:[1]
I found out GooglePay is not a payment gateway but rather a ladder to gateway, so you have to integrate a payment gateway system with google and from the list i recommend STRIPE. which i will be explaining below.
I came across two. options to achieve this.
- Google Pay plugin - This make use of STRIPE Payment Gateway Automatically.
- Flutter Google Pay - This has multiple, custom payment gateway you can make use of.
REQUIREMENT
Ensure you have your stripe account setup - If you don't already visit Stripe Payment Gateway to setup your account
The first plugin Google Pay plugin Ensure you initialize the plugin with your stripe payment secret key
GooglePay.initializeGooglePay("pk_test_H5CJvRiPfCrRS44bZJLu46fM00UjQ0vtRN");
This plugin has code structure as this.
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:google_pay/google_pay.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _platformVersion = 'Unknown';
String _googlePayToken = 'Unknown';
@override
void initState() {
super.initState();
initPlatformState();
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await GooglePay.platformVersion;
} on PlatformException {
platformVersion = 'Failed to get platform version.';
}
await GooglePay.initializeGooglePay("pk_test_H5CJvRiPfCrRS44bZJLu46fM00UjQ0vtRN");
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Column(
children: <Widget>[
Text('Running on: $_platformVersion\n'),
Text('Google pay token: $_googlePayToken\n'),
FlatButton(
child: Text("Google Pay Button"),
onPressed: onButtonPressed,
)
]
),
),
),
);
}
void onButtonPressed() async{
setState((){_googlePayToken = "Fetching";});
try {
await GooglePay.openGooglePaySetup(
price: "5.0",
onGooglePaySuccess: onSuccess,
onGooglePayFailure: onFailure,
onGooglePayCanceled: onCancelled);
setState((){_googlePayToken = "Done Fetching";});
} on PlatformException catch (ex) {
setState((){_googlePayToken = "Failed Fetching";});
}
}
void onSuccess(String token){
setState((){_googlePayToken = token;});
}
void onFailure(){
setState((){_googlePayToken = "Failure";});
}
void onCancelled(){
setState((){_googlePayToken = "Cancelled";});
}
}
The second plugin Flutter Google Pay which make use of other payment gateway
you can see the list here Payment Gateways
This plugin has two methods for you initialization - either using stripe or other gateways
FOR STRIPE USE THIS METHOD AND INITIALIZE WITH YOUR STRIPE SECRET KEY _makeStripePayment() async { var environment = 'rest'; // or 'production'
if (!(await FlutterGooglePay.isAvailable(environment))) {
_showToast(scaffoldContext, 'Google pay not available');
} else {
PaymentItem pm = PaymentItem(
stripeToken: 'pk_test_1IV5H8NyhgGYOeK6vYV3Qw8f',// stripe public key
stripeVersion: "2018-11-08",
currencyCode: "usd",
amount: "0.10",
gateway: 'stripe');
FlutterGooglePay.makePayment(pm).then((Result result) {
if (result.status == ResultStatus.SUCCESS) {
_showToast(scaffoldContext, 'Success');
}
}).catchError((dynamic error) {
_showToast(scaffoldContext, error.toString());
});
}
}
FOR OTHER PAYMENT GATEWAYS
_makeCustomPayment() async {
var environment = 'rest'; // or 'production'
if (!(await FlutterGooglePay.isAvailable(environment))) {
_showToast(scaffoldContext, 'Google pay not available');
} else {
///docs https://developers.google.com/pay/api/android/guides/tutorial
PaymentBuilder pb = PaymentBuilder()
..addGateway("example")
..addTransactionInfo("1.0", "USD")
..addAllowedCardAuthMethods(["PAN_ONLY", "CRYPTOGRAM_3DS"])
..addAllowedCardNetworks(
["AMEX", "DISCOVER", "JCB", "MASTERCARD", "VISA"])
..addBillingAddressRequired(true)
..addPhoneNumberRequired(true)
..addShippingAddressRequired(true)
..addShippingSupportedCountries(["US", "GB"])
..addMerchantInfo("Example");
FlutterGooglePay.makeCustomPayment(pb.build()).then((Result result) {
if (result.status == ResultStatus.SUCCESS) {
_showToast(scaffoldContext, 'Success');
} else if (result.error != null) {
_showToast(context, result.error);
}
}).catchError((error) {
//TODO
});
}
}
Solution 2:[2]
You should have no problem to use g pay with in-app. There is no need to write specific code for that. You just need to make sure you are setting up your merchant in the google billing platform. Check out this tutorial https://medium.com/flutter-community/in-app-purchases-with-flutter-a-comprehensive-step-by-step-tutorial-b96065d79a21
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | eclat_soft |
Solution 2 | M4trix Dev |