I am Ayesha Iftikhar and I am creating this gist to keep all the most commonly used codes in one place. This will have all common code snippets which are basic building blocks of any flutter application. Like, basic widgets and their commonly used properties. Setting up a project with Firebase and Firebase Authentications.
Note: Errors and Omissions are expected and your contributions will be appreciated.
Container is the most commonly user widget and it almost supports each kind of widgets and most common painting and layout and sizing widgets.
Container(
alignment: Alignment.center,
padding: EdgetInsets.all(10),
margin: EdgeInsets.all(5),
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(
width: 2.0,
color: Colors.grey
),
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: Colors.black,
offset: Offset(0, 10),
blurRadius: 10
),
],
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [Colors.purple, Colors.orange]
),
)
),
- Create a Stripe account and project
- Retrieve a publishable key & secret key from the Stripe dashboard
Requires AndroidX
android.useAndroidX=true
android.enableJetifier=true
And minSDKVersion 19.
- Add the dependency in pubspec.yanl
stripe_payment:
- Get the packages:
flutter pub add stripe_payment
- Import the dependency:
import 'package:stripe_payment/stripe_payment.dart';
- Create a stateful widget class and setup options in initState() method:
@override
void initState(){
super.initState();
StripePayment.setOptions(StripeOptions(
publishableKey: "YOUR_PUBLISHABLE_KEY,
merchantId: 'YOUR_MERCHANT_ID',
androidPayMode: 'test', // DO NOT FORGET TO CHANGE THIS TO Live FOR REAL TIME PAYMENTS INTEGRATIONS.
));
}
- Setup Credit card instance, I am using one of the credit cards given in stripe documentation at here.
CreditCard _card = CreditCard(
number: "5555555555554444", // card number
expMonth: 12,
expYear: 27,
);
- Get billing address:
BillingAddress billingAddress = billingAddress = BillingAddress(
name: "Username",
line1: "Address Line 1",
line2: "Address Line 2",
postalCode: "Postal Code",
city: "City",
state: "State",
country: "Country",
);
- The following piece of code with generate a transaction:
class StripeService {
static String apiBase = 'https://api.stripe.com/v1';
static Uri paymentApiUrl = Uri.parse('$apiBase/payment_intents');
static Map<String, String> headers = {
'Authorization': 'Bearer $secret',
'Content-Type': 'application/x-www-form-urlencoded'
};
static Future<StripeTransactionResponse> payWithCard({
@required String amount,
@required String currency,
@required CreditCard card,
@required String description,
@required String name,
@required String phone,
@required String email,
@required BillingAddress billingAddress,
}) async {
try {
/// billing address
BillingDetails billingDetails = BillingDetails(
address: billingAddress,
email: email,
name: name,
phone: phone,
);
/// Payment Method Request
PaymentMethodRequest paymentMethodRequest = PaymentMethodRequest(
billingAddress: billingAddress,
card: card,
);
/// Payment Method based on Payment Method Request
var paymentMethod =
await StripePayment.createPaymentMethod(paymentMethodRequest);
/// Payment Intent from Server
var paymentIntent = await createPaymentIntent(
amount: amount,
currency: currency,
description: description,
card: card,
paymentMethod: paymentMethod,
);
/// confirm payment method
var response = await StripePayment.confirmPaymentIntent(PaymentIntent(
paymentMethod: paymentMethodRequest,
clientSecret: paymentIntent['client_secret'],
paymentMethodId: paymentMethod.id,
));
if (response.status == 'succeeded') {
return StripeTransactionResponse(
message: 'Transaction successful', success: true);
} else {
return StripeTransactionResponse(
message: 'Transaction failed', success: false);
}
} on PlatformException catch (err) {
return getPlatformExceptionErrorResult(err);
} catch (e) {
print('Pay with card $e');
return null;
}
}
static getPlatformExceptionErrorResult(err) {
String message = 'Something went wrong';
if (err.code == 'cancelled') {
message = 'Transaction cancelled';
}
return StripeTransactionResponse(message: message, success: false);
}
static Future<Map<String, dynamic>> createPaymentIntent({
@required String amount,
@required String currency,
@required String description,
@required PaymentMethod paymentMethod,
@required CreditCard card,
}) async {
try {
Map<String, dynamic> body = {
'amount': amount,
'currency': currency,
'payment_method_types[]': 'card',
'description': description,
};
var response =
await http.post(paymentApiUrl, body: body, headers: headers);
return jsonDecode(response.body);
} catch (e) {
print('Create Payment Intent: $e');
return null;
}
}
}
class StripeTransactionResponse {
String message;
bool success;
StripeTransactionResponse({this.message, this.success});
}
- I have used the approach of saving the card to firebase before using it to make transaction, you can use this piece of code to store card information to fiirebase:
_controller.cardRef.add({
'userid': "User id",
'card_number': "Card Number",
'holder_name': "Card Holder Name",
'csv': "CSV",
'expiry_date': "Expiry Date",
'Time': DateTime.now(), // track the time of action
}).then((snapshot) {
showToast(message: 'Card added successfully.');
Get.back();
});
- Call the payWithCard() function to make transaction:
try{
StripeService.payWithCard(
amount:"1000",
currency: "USD",
card: _card,
description: "Reason of Transaction",
name: "Username",
phone: "phone number",
email: "email",
billingAddress: billingAddress
).then((transactionRespone) {
if (transactionRespone.success) {
print('success');
}
});
}catch(e){
print(e);
}
- Note: Stripe process each transaction amount in the smallest possible unit of the mentioned currenct. So you need to multiply the entered amount with 100 to make transaction in correct amount and digits. Let's say user has entered 1000... Stripe API will consider it as 10.00 and transaction only 10 from user's bank account so it is important to multiply it with 100 before proceeding further.