Why not displaying card - flutter

I want to intigrate stripe payment but i got this error
** FlowController must be successfully initialized using configureWithPaymentIntent() or configureWithSetupIntent() before calling presentPaymentOptions()**
How solve this error also it is not displaying any card
Center(
child: ElevatedButton(
onPressed: () {
intpayment(email: "email,amount: 50.0);
},
child: Text("Pay20\$"),
),
),
Future<void> intpayment(
{required String email, required double amount})async{
try{
final response= await http.post(Uri.parse("https://api.stripe.com/v1/payment_intents")
,body:{
"receipt_email": email,
"amount": amount.toInt().toString(),
"currency": "usd"
},
headers: {
'Authorization': 'Bearer ' + 'key',
'Content-Type': 'application/x-www-form-urlencoded'
}
);
final jsonresponse=jsonDecode(response.body); Stripe.instance.initPaymentSheet(paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: jsonresponse['paymentIntent'],
merchantDisplayName: 'Zohaib',
));
await Stripe.instance.presentPaymentSheet();
Fluttertoast.showToast(
msg: "payment successfully",
);
}
catch(e){
if (e is StripeException) {
Fluttertoast.showToast(
msg: "Stripe error $e",
);
}
Fluttertoast.showToast(
msg: "$e",
toastLength: Toast.LENGTH_SHORT, );
}
}

You need to create the PaymentIntent on the server-side and not within your flutter app.
final response= await http.post(Uri.parse("https://api.stripe.com/v1/payment_intents")
,body:{
"receipt_email": email,
"amount": amount.toInt().toString(),
"currency": "usd"
},
headers: {
'Authorization': 'Bearer ' + 'key',
'Content-Type': 'application/x-www-form-urlencoded'
}
);
Instead of calling the Stripe API directly as you did in the code above, you should call your own API and generate a Payment Intent and just send the client_secret to your flutter App, otherwise you would be exposing your secret key and thus giving access to your data. This is described here.
Once you do this server-side part the rest is explained here.

Related

Issue in displaying card in stripe payment intigration

I want to intigrate stripe payment but i got this error Instance of 'StripeConfigException Also my when i click on pay button it is not showing any type of card. I want to print jsonresponse["emphermalKey"] and jsonresponse["customer"] but these show null value.I also put api key correctly . Please solve my issue i am stuck in stripe payment for couple of days Here is my stripe log which shoes null value.
{
"customer": null,
"description": null,
"invoice": null,
"last_payment_error": null,
"latest_charge": null,
"next_action": null,
"on_behalf_of": null,
"payment_method": null,
"payment_method_options": {
"card": {
"installments": null,
"mandate_options": null,
"network": null,
"request_three_d_secure": "automatic"
}
"processing": null,
"review": null,
"setup_future_usage": null,
"shipping": null,
"source": null,
"statement_descriptor": null,
"statement_descriptor_suffix": null,
"status": "requires_payment_method",
"transfer_data": null,
"transfer_group": null
}
my code
Center(
child: ElevatedButton(
onPressed: () {
intpayment(email: "email,amount: 50.0);
},
child: Text("Pay20\$"),
),
),
Function
Future<void> intpayment(
{required String email, required double amount})async{
try{
final response= await http.post(Uri.parse("https://api.stripe.com/v1/payment_intents")
,body:{
"receipt_email": email,
"amount": amount.toInt().toString(),
"currency": "usd"
},
headers: {
'Authorization': 'Bearer ' + 'key',
'Content-Type': 'application/x-www-form-urlencoded'
}
);
final jsonresponse=jsonDecode(response.body); Stripe.instance.initPaymentSheet(paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: jsonresponse['paymentIntent'],
merchantDisplayName: 'Zohaib',
customerId: jsonresponse['customer'],
customerEphemeralKeySecret: jsonresponse['ephemeralKey'],
));
await Stripe.instance.presentPaymentSheet();
Fluttertoast.showToast(
msg: "payment successfully",
);
}
catch(e){
if (e is StripeException) {
Fluttertoast.showToast(
msg: "Stripe error $e",
);
}
Fluttertoast.showToast(
msg: "$e",
toastLength: Toast.LENGTH_SHORT, );
}
}
I think issue in this line when I comment out this the error remove but card is not displying
await Stripe.instance.presentPaymentSheet();
If you don't have any value in jsonresponse it means you backend hasn't been able to return them, and mostly because it didn't have the correct Secret Key or having some issue sending Stripe API itself.
The fastest way to isolate the issue is looking at your backend log, or your Stripe Request Logs https://dashboard.stripe.com/test/logs and find the specific call from your backend -> Stripe.

Issue is in displaying card in stripe payment

I want to intigrate stripe payment but i got this error
Instance of 'StripeConfigException
Also my when i click on pay button it is not showing any type of card.
I want to print jsonresponse["emphermalKey"] and jsonresponse["customer"] but these show null value .
Please solve my issue i am stuck in stripe payment for couple of days
Here is my stripe log which shoes null value
{
"customer": null,
"description": null,
"invoice": null,
"last_payment_error": null,
"latest_charge": null,
"next_action": null,
"on_behalf_of": null,
"payment_method": null,
"payment_method_options": {
"card": {
"installments": null,
"mandate_options": null,
"network": null,
"request_three_d_secure": "automatic"
}
"processing": null,
"review": null,
"setup_future_usage": null,
"shipping": null,
"source": null,
"statement_descriptor": null,
"statement_descriptor_suffix": null,
"status": "requires_payment_method",
"transfer_data": null,
"transfer_group": null
}
my code
Center(
child: ElevatedButton(
onPressed: () {
intpayment(email: "email,amount: 50.0);
},
child: Text("Pay20\$"),
),
),
Function
Future<void> intpayment(
{required String email, required double amount})async{
try{
final response= await http.post(Uri.parse("https://api.stripe.com/v1/payment_intents")
,body:{
"receipt_email": email,
"amount": amount.toInt().toString(),
"currency": "usd"
},
headers: {
'Authorization': 'Bearer ' + 'key',
'Content-Type': 'application/x-www-form-urlencoded'
}
);
final jsonresponse=jsonDecode(response.body); Stripe.instance.initPaymentSheet(paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: jsonresponse['paymentIntent'],
merchantDisplayName: 'Zohaib',
customerId: jsonresponse['customer'],
customerEphemeralKeySecret: jsonresponse['ephemeralKey'],
));
await Stripe.instance.presentPaymentSheet();
Fluttertoast.showToast(
msg: "payment successfully",
);
}
catch(e){
if (e is StripeException) {
Fluttertoast.showToast(
msg: "Stripe error $e",
);
}
Fluttertoast.showToast(
msg: "$e",
toastLength: Toast.LENGTH_SHORT, );
}
}

In Flutter Is that possible to call API request in firebase Messaging BackgroundHandler?

I have implemented chat message app in which user can
reply to chat from push
notification when app is killed/background/foreground.
But when app is in Terminated state API call not work in
firebaseMessagingBackgroundHandler.
Its stuck on sendNotification function.
Code to handle background events:
Future<void>
firebaseMessagingBackgroundHandler(RemoteMessage message)
async {
await GetStorage.init();
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform);
//Call HTTP request <Stuck here
sendNotification(
personUid,
title,
body,
notificationTypeId,
chatRoomId,
userTokenDummy,
userToken,
serverKey,
currentUserId,
currentUserToken,
);
}
Here is a code for API request:
sendNotification({
required String personUid,
required String title,
required String body,
required int notificationTypeId,
String? chatRoomId,
String? userTokenDummy,
String? userToken,
String? serverKey,
String? currentUserId,
String? currentUserToken,
}) async {
try {
final response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
HttpHeaders.contentTypeHeader:
'application/json',
HttpHeaders.authorizationHeader: 'key=$serverKey'
},
body: jsonEncode(
<String, dynamic>{
"data": <String, dynamic>{
"title": title,
"body": body,
"click_action": "FLUTTER_NOTIFICATION_CLICK",
"id": "1",
"status": "done",
"senderId": currentUserId,
"senderToken": currentUserToken,
"notificationTypeId": notificationTypeId,
"chatRoomId": chatRoomId,
},
"android": {
"priority": "high",
},
"apns": {
"headers": {"apns-priority": "10"}
},
"to": userToken,
"content_available": true,
"mutable-content": 1,
"priority": "high",
},
),
);
return response;
} catch (e) {
console(e.toString());
}
}
Yes,you can call Http request inside firebaseMessagingBackgroundHandler. But make sure that this api is not taking too much time. Because long and intensive tasks impacts on device performance. Also make sure that there is not exception or error in the api which causes the device to freeze.
To make sure that api is not running forever place a timeout in http class.
for more refer to firebase documentation : https://firebase.google.com/docs/cloud-messaging/flutter/receive

Flutter Desktop Auth

As we all know desktop application has no auth support so any one can help me with this.
Future<http.Response> signUp(
String email,
String password,
) async {
final uri =
Uri.parse("https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=$apiKey");
final headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer token',
};
Map<String, dynamic> body = {
"email": "xyz23#gmail.com",
"password": "password",
"returnSecureToken":true,
};
String jsonBody = json.encode(body);
final encoding = Encoding.getByName('utf-8');
http.Response response = await http.post(
uri,
headers: headers,
body: jsonBody,
encoding: encoding,
);
print(response.statusCode);
print(response.body);
jsonResponse = json.decode(response.body);
// box.write("token", jsonResponse['refreshToken']);
// oneTimeToken = jsonResponse['refreshToken'];
// print(oneTimeToken);
if (box.read('token') != null) {
Fluttertoast.showToast(
msg: 'Account Created Successfully',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);;setState(() {
loading = false;
});
} else if (response.statusCode != 200) {
setState(() {
loading = false;
});
Fluttertoast.showToast(
msg: 'Account Already existing \n or missing data',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
return response;
}
Error:
flutter: {
"error": {
"code": 401,
"message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"errors": [
{
"message": "Invalid Credentials",
"domain": "global",
"reason": "authError",
"location": "Authorization",
"locationType": "header"
}
],
"status": "UNAUTHENTICATED",
"details": [
{
"#type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "ACCESS_TOKEN_TYPE_UNSUPPORTED",
"metadata": {
"method": "google.cloud.identitytoolkit.v1.AuthenticationService.SignInWithPassword",
"service": "identitytoolkit.googleapis.com"
}
}
]
}
}
I am having this error can any one tell me what is this (OAuth 2 access token).I used this code on mongodb Works fine.
or
if anyone have any other solution it will be big help if provided.
thankyou.
get solution for flutter desktop auth.
Assuming you are NOT using OAuth 2.0 for your API, remove the authorization header from your sign up request and it should work.
final headers = {
'Content-Type': 'application/json',
//Remove this 'Authorization': 'Bearer token',
};
Try it out on the command line using your API key
curl --request POST \
'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=[YOUR_API_KEY]' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{"email":"test#test.com","password":"password123"}' \
--compressed
https://cloud.google.com/identity-platform/docs/reference/rest/v1/accounts/signUp
https://support.google.com/googleapi/answer/6158862?hl=en&ref_topic=7013279
https://support.google.com/googleapi/answer/6158849?hl=en&ref_topic=7013279
https://developers.google.com/identity/protocols/OAuth2#libraries

Why can't I send an FCM message to any Topic other than "test_fcm_topic" in my Flutter app?

I can send an FCM message to my Flutter app when the app has subscribed to "test_fcm_topic" as a topic. But if I subscribe to anything else IE: "redrobin" I don't receive the notification. I've tried sending from both the Flutter app and from Postman. In both cases the terminal shows the instance is received but there is no sound or notification popup.
I'm completely baffled as to why I cannot change the topic to anything other than "test_fcm_topic". Why would it work with one topic but not in the other? How can I even begin to troubleshoot?
Here's the code I use to subscribe;
FCMConfig.init(onBackgroundMessage: firebaseMessagingBackgroundHandler).then((value) {FCMConfig.subscribeToTopic("test_fcm_topic");});
Here's the send code in Flutter;
void send() async {
await http.post(
'https://fcm.googleapis.com/fcm/send',
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$serverToken',
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{
'body': 'This is a body',
'title': 'Banana'
},
'priority': 'high',
'data': <String, dynamic>{
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
},
'to': '/topics/test_fcm_topic',
},
),
);
}
For Postman I use these key pairs in the headers
Key: Authorization Value: key= server key
Key: Content-Type: Value: application/json
And this is the Raw JSON Body;
{
"to" : "/topics/test_fcm_topic",
"collapse_key" : "type_a",
"notification" : {
"body" : "Body of Your Notification",
"title": "Banana"
},
"data" : {
"body" : "This is a body",
"title": "Title of Your Notification in Title",
"key_1" : "Value for key_1",
"key_2" : "Value for key_2"
}
}
Using your code like this works like a charm when testing on my device:
void send(String serverToken) async {
Response response = await post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization':'key=$serverToken'
},
body: jsonEncode(
<String, dynamic>{
'notification': <String, dynamic>{'body': 'This is a body', 'title': 'Banana'},
'priority': 'high',
'data': <String, dynamic>{'audioid': '139', 'title': 'done all over time', 'name': 'Greengirl'},
'to': '/topics/hi',
},
),
);
print(response.body);
}
But please note, that you must subscribe to the topic 'hi3' used in this example.
By running :
FirebaseMessaging.instance.subscribeToTopic('hi3'); on the client you want to receive these broadcasts.
Output of the function above is:
I/flutter (18090): {"message_id":1225534686323630021}
followed by:
D/FLTFireMsgReceiver(18090): broadcast received for message
They even run faster than firebase console push notifications.