How can I get token from stripe payment flutter? - flutter

I'm doing stripe payment method very first time and the Api developer told me to give him token for stripe payment. I've seen tutorial about but couldn't find about token from anywhere. I also have implemented it and success the payment but how to find token now. I need help.
Thanks
Here is how I was trying to do but getting error
Future<void> makePayment() async {
try {
paymentIntent = await createPaymentIntent("20", "USD");
if (paymentIntent == null) {
// handle the error
print("Error creating payment intent");
return;
}
await Stripe.instance
.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntent?['client_secret'],
// applePay: PaymentSheetApplePay(merchantCountryCode: "+971"),
// googlePay: PaymentSheetGooglePay(testEnv: true, currencyCode: "AE"),
style: ThemeMode.dark,
merchantDisplayName: "Marketingo"))
.then((value) {});
displayPaymentSheet();
var tokenData = await Stripe.instance.createToken(params);
if (tokenData.tokenId != null) {
var token = tokenData.tokenId;
// Use the token to complete the payment on your server.
}
} catch (e) {
print("exception $e");
}
}

Related

Getting response after executing entire code

I am trying to get some information from a database which I do get eventually, but my if conditions are checked first before getting the data and prints the data after completing the checking of the if conditions, even though I have used await to wait for the data to arrive and then continue.
Future reg() async {
getData().then((value) async {
print(value["serverIP"]);
print(value["port"]);
print(value["passwordMain"]);
Dio dio = Dio();
Response response = await dio.get(
'http://${value["serverIP"]}:${value["port"]}/${value["passwordMain"]}/reg/${controllerEmail.text}/${controllerPassword.text}/${controllerUsername.text}');
print(response.data);
return response;
});
ElevatedButton(
onPressed: () async {
if (!controllerEmail.text.endsWith("#gmail.com") &
!controllerEmail.text.endsWith("#gmail.com ") &
!controllerEmail.text.endsWith("#email.com") &
!controllerEmail.text.endsWith("#email.com ") &
!controllerEmail.text.endsWith("#hotmail.com") &
!controllerEmail.text.endsWith("#hotmail.com ")) {
if (controllerEmail.text.endsWith(" ")) {
controllerEmail.text =
controllerEmail.text.replaceAll(" ", "");
}
showErrorDialog(context, 'Unknown Email Address',
'Try Changing the Email to one of the Providers we Support.');
} else if ((controllerPassword.text !=
controllerRePassword.text) |
controllerPassword.text.isEmpty) {
showErrorDialog(context, 'Passwords Do not Match/Empty',
'Please Re-Type your Passwords as they do not Match, or are Empty');
} else {
var response = await reg();
if (response != null) {
if (response.data == "done") {
showErrorDialog(context, "Done",
"Your Account has been Created, please Log in");
} else if (response.data == "key") {
showErrorDialog(
context,
"Incorrect API Key/Main Server Password",
"The API Key (Main Server Password) is Incorrect. Kindly, Ensure the Key.");
} else if (response.data == "email") {
showErrorDialog(context, "Account Already Exists",
"An Account already exists with this Email");
} else if (response.data == "username") {
showErrorDialog(context, "Account Already Exists",
"An Account already exists with this Username");
}
}
}
},
child: const Text("Sign Up"),
),
You're missing a return in your reg() function. Add one before your getData() call like this:
Future reg() async {
try {
return getData().then((value) async {
Dio dio = Dio();
Response response = await dio.get(
'http://${value["serverIP"]}:${value["port"]}/${value["passwordMain"]}/reg/${controllerEmail.text}/${controllerPassword.text}/${controllerUsername.text}');
return response;
});
} catch (e) {}
}
Now the function should be properly awaited because it is now returning a promise instead of nothing.
Alternatively, you might prefer to rewrite it using more async/await for easier comprehension, like this:
Future reg() async {
try {
const value = await getData();
Dio dio = Dio();
Response response = await dio.get(
'http://${value["serverIP"]}:${value["port"]}/${value["passwordMain"]}/reg/${controllerEmail.text}/${controllerPassword.text}/${controllerUsername.text}');
return response;
} catch (e) {}
}
Credit: https://stackoverflow.com/a/74238420/13909069

signInWithCredential returns null without any error in flutter

I'm using Firebase to sign in with phone number it does send OTP message but when I'm trying to sign with credentials using the OTP I got and the verification ID (they're not null they do have values) it returns null here (result is null) not throwing any errors
here's my code
static Future<UserCredential?> verifyOTP(
String verificationId, String otp) async {
UserCredential? result;
try {
print(otp);
print(verificationId);
PhoneAuthCredential credential = PhoneAuthProvider.credential(
verificationId: verificationId,
smsCode: otp,
);
result = await _firebaseAuth?.signInWithCredential(credential);
User? user = _firebaseAuth?.currentUser;
print('user $user');
print('results $result');
} on FirebaseAuthException catch (error) {
print(error);
}
return result;
}
By signInWithCredential do you mean Email and Password Firebase Authentication?
If so you should use signInWithEmailAndPassword Firebase Auth method.
Example below:
try {
await _firebaseAuth.signInWithEmailAndPassword(
email: email,
password: password,
);
} catch (_) {
throw const LogInWithEmailAndPasswordFailure();
}

Google pay button not showing in flutter_stripe package payment sheet

I used flutter_stripe: ^3.3.0 to implement stripe payment, everything goes well but I can't see google pay button on top of stripe payment sheet. I have enable google pay according to https://docs.page/flutter-stripe/flutter_stripe/sheet. and below is what i am getting.
Future<void> makePayment(
{String amount,String currency}) async {
try {
paymentIntentData = await createPaymentIntent(amount, currency);
if (paymentIntentData != null) {
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
applePay: true,
googlePay: true,
testEnv: true,
merchantCountryCode: 'US',
merchantDisplayName: 'Prospects',
customerId: paymentIntentData['customer'],
paymentIntentClientSecret: paymentIntentData['client_secret'],
customerEphemeralKeySecret: paymentIntentData['ephemeralKey'],
));
displayPaymentSheet();
}
} catch (e, s) {
print('exception:$e$s');
}
}

'PresentPaymentSheetParameters' is deprecated and shouldn't be used. Parameters are now inherited from initPaymentSheet

I am integrating Stripe Payment Gateway into my e-commerce application. I am new to stripe payment gateway, I am facing a depreciation error which is as
'parameters' is deprecated and shouldn't be used. Params are now inherited from initPaymentSheet so this 'parameters' can be removed.
The current stripe plugin I am using is flutter_stripe: ^3.3.0. Just want to know how to fix this depreciation issue. Attaching the error screenshot also
CODE IS AS :
displayPaymentSheet(OrderProvider orderProvider) async {
try {
await Stripe.instance
.presentPaymentSheet(
parameters: PresentPaymentSheetParameters(
clientSecret: paymentIntentData!['client_secret'],
confirmPayment: true,
))
.then((newValue) {
print('payment intent ${paymentIntentData!['id']}');
print('payment intent ${paymentIntentData!['client_secret']}');
print('payment intent ${paymentIntentData!['amount']}');
print('payment intent $paymentIntentData');
//orderPlaceApi(paymentIntentData!['id'].toString());
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: const Text("Paid successfully")));
orderProvider.success = true;
Navigator.pop(context);
setState(() {
paymentIntentData = null;
});
}).onError((error, stackTrace) {
print('Exception/DISPLAYPAYMENTSHEET==> $error $stackTrace');
});
} on StripeException catch (e) {
print('Exception/DISPLAYPAYMENTSHEET==> $e');
showDialog(
context: context,
builder: (_) => AlertDialog(
content: Text("Cancelled "),
));
} catch (e) {
print('$e');
}
}
Try using initPaymentSheet.
await Stripe.instance
.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: "",
),
)

Flutter Stripe paymentsheet is opening webpage (hooks.stripe.com) while processing payments

I am developing a flutter application which uses stripe for payments. I am using https://pub.dev/packages/flutter_stripe for this.
Everything is working fine but whenever I initiate payments I always get a webpage middleware (Screenshots attached). What am I doing wrong?
Here is my implementation in Flutter
Future<void> makePayment(String planName, String type) async {
Fluttertoast.showToast(msg: "initiating Payments, Please wait.");
ApiProvider provider = ApiProvider();
final tokenResponse = await provider
.getPaymentToken(PlanPayment(planName: planName, type: type));
if (tokenResponse != null) {`
var _service = locator<NavigationService>();
String secret = tokenResponse.clientSecret;
// make a get call from this url
Map<String, dynamic> paymentIntentData = Map();
await payment.Stripe.instance.initPaymentSheet(
paymentSheetParameters: payment.SetupPaymentSheetParameters(
merchantCountryCode: 'IN',
testEnv: true,
paymentIntentClientSecret: secret,
googlePay: true,
));
try {
// await Stripe.instance.handleCardAction(secret);
await payment.Stripe.instance.presentPaymentSheet().then((value) {});
await payment.Stripe.instance
.confirmPaymentSheetPayment()
.then((value) async {
// await _service.pushNamed(paymentStatus, args: {'isSuccess': true});
});
} catch (e) {
// await _service.pushNamed(paymentStatus, args: {'isSuccess': false});
print("Stripe error" + e.toString());
}
await provider
.confirmPayment(tokenResponse.transactionId)
.then((value) async {
await _service
.pushReplacementNamed(paymentStatus, args: {"isSuccess": value});
});
}
}
`
Maybe you have a webhook put in your account?
1)Provide valid Secret key
2)Provide valid Publisable key
3)Update flutterstripe pacakge
4)provide valid currency code to create stripe account country
ex :- stripe account create india to inr etc..
5)Right Way to implemet
- Main.dart to main method run app to implemet
ex :--
Stripe.publishableKey = "your publishable key ";
- create controller / method
code:-
Map<String, dynamic>? paymentIntentData;
Future<void> makePayment({amount}) async {
try {
paymentIntentData =
await createPaymentIntent(amount: amount, currency: 'INR');
if (paymentIntentData != null) {
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
// applePay: true,
googlePay: const PaymentSheetGooglePay(merchantCountryCode: 'INR'),
merchantDisplayName: "PGA",
customerId: paymentIntentData!['customer'],
paymentIntentClientSecret: paymentIntentData!['client_secret'],
customerEphemeralKeySecret: paymentIntentData!['ephemeralkey'],
));
}
displayPaymentSheet();
} catch (err) {
logger.e(err);
}
}
void displayPaymentSheet() async {
try {
await Stripe.instance.presentPaymentSheet();
Get.snackbar("PaymentInfo", "Payment Successfully");
} on Exception catch (e) {
if (e is StripeException) {
logger.e(e, "Error From Stripe");
} else {
logger.e(e, "Unforeseen error");
}
} catch (e) {
logger.e("exeption === $e");
}
}
var id = "";
createPaymentIntent({amount, currency}) async {
try {
Map<String, dynamic> body = {
'amount': calculateAmount(amount: amount),
'currency': currency,
'payment_method_types[]': 'card'
};
var response = await http.post(
Uri.parse('https://api.stripe.com/v1/payment_intents'),
headers: {
'Authorization':
'Bearer YourSecretKey',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: body,
);
if (response.statusCode == 200) {
var decode = jsonDecode(response.body);
logger.e(decode);
id = decode['id'];
return decode;
}
} catch (e) {
logger.e(e, "error charging user");
}
}
calculateAmount({amount}) {
logger.e(amount.round());
final a = (int.parse(amount.toString())) * 100;
logger.e(a.toString());
update();
return a.toString();
}
6) How to Access Stripe payment :-
ex :- any button click
ontap : (){
makePayment(
amount: "200")
}