Unhandled Exception: Instance of 'StripeConfigException'..// - flutter

I want to intigrate stripe payment method but i am facing error.In Stripe log it say successfull but it through error in flutter
.
I also check my publish key. Please solve this issue
button
Center(
child: ElevatedButton(
onPressed: () {
intpayment(email: "email);
},
child: Text("Pay20\$"),
),
),
Future 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, );
}
}

Related

Instance of 'StripeConfigException'

I want to intigrate stripe payment method but i am facing error.I am unable to show paymentsheet.Also when i click on pay button this error happened
Instance of 'StripeConfigException'
D/CompatibilityChangeReporter(21470): Compat change id reported: 147798919; UID 10020; state: ENABLED
I/ForceDarkHelperStubImpl(21470): setViewRootImplForceDark: false for , reason: AppDarkModeEnable
I/ForceDarkHelperStubImpl(21470): setViewRootImplForceDark: false for , reason: AppDarkModeEnable
I/ForceDarkHelperStubImpl(21470): setViewRootImplForceDark: false for , reason: AppDarkModeEnable
Center(
child: ElevatedButton(
onPressed: () {
intpayment(email: "email);
},
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, );
}
}

firebase phone authentication not sending sms, got this Error [SmsRetrieverHelper] Timed out waiting for SMS

I'm having a problem with firebase phone authentication, yesterday I was testing login with phoneNumber but it didn't work. I tested it with different devices, smsCode doesn't send as to verify login. two weeks ago it was just working fine
I tried to upgrade all the packages including firebase_core and firebase_auth but nothing has changed.
firebase_core: ^2.4.0
cloud_firestore: ^4.2.0
firebase_auth: ^4.2.1
this is my code:
ElevatedButton(
onPressed: () {
if (otpVisibility) {
verifyOTP();
} else {
loginWithPhone();
}
},
child: Padding(
padding: EdgeInsets.symmetric(vertical: 1.h, horizontal: 1.h),
child: Text(
otpVisibility ? "verify" : "login",
style: TextStyle(fontSize: 15.sp, fontFamily: 'Cairo'),
),
),
),
this is the error I keep getting:
W/BpBinder( 2464): Slow Binder: BpBinder transact took 433ms, interface=com.google.android.gms.auth.api.phone.internal.ISmsRetrieverApiService, code=1 oneway=false
W/FirebaseAuth( 2464): [SmsRetrieverHelper] Timed out waiting for SMS.
void loginWithPhone() async {
auth.verifyPhoneNumber(
phoneNumber:_prefix + phoneController.text,
verificationCompleted: (PhoneAuthCredential credential) async {
await auth.signInWithCredential(credential).then((value) {
if (value.user != null) {
print("Done !!");
print("You are name saved successfully");
print("You are logged in successfully");
} else {
print("Failed!!");
}
}).catchError((e) {
Fluttertoast.showToast(msg: 'Something Went Wrong: ${e.toString()}');
});
},
verificationFailed: (FirebaseAuthException e) {
print(e.message);
},
codeSent: (String verificationId, int resendToken) {
otpVisibility = true;
verificationID = verificationId;
setState(() {});
},
codeAutoRetrievalTimeout: (String verificationId) {},
timeout: const Duration(seconds: 20),
);
}
void verifyOTP() async {
PhoneAuthCredential credential = PhoneAuthProvider.credential(
verificationId: verificationID, smsCode: otpController.text);
await auth.signInWithCredential(credential).then((value) {
print("You are logged in successfully");
uploadUserInfoToFirebase();
_nameSaver();
Fluttertoast.showToast(
msg: "You are logged in successfully",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.CENTER,
timeInSecForIosWeb: 1,
backgroundColor: KInActiveColor,
textColor: Colors.white,
fontSize: 12.sp);
Navigator.push(
context, MaterialPageRoute(builder: (context) => HomePage()));
});
}
}
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: '${_prefix}${phoneController.text}',
verificationCompleted: (PhoneAuthCredential credential) async {
await auth.signInWithCredential(credential).then((value) {
if (value.user != null) {
print("Done !!");
print("You are name saved successfully");
print("You are logged in successfully");
} else {
print("Failed!!");
}
}).catchError((e) {
Fluttertoast.showToast(msg: 'Something Went Wrong: ${e.toString()}');
});
},
verificationFailed: (FirebaseAuthException e) {
print(e.message);
},
codeSent: (String verificationId, int resendToken) {
otpVisibility = true;
verificationID = verificationId;
setState(() {});
},
codeAutoRetrievalTimeout: (String verificationId) {},
timeout: const Duration(seconds: 20),
);
timeout: Duration(seconds: 120));
}

How to pass this 'Dio Post Request' Problem in Flutter

I have to send an object from the request. Although it works on Swagger, I cannot send it from my flutter code. When I was trying it, it always gave me Http status error 400 This problem is coming my wrong request. I examined the code of the Internet. I thought I implemented it correctly but It still does not work. Please, could you help me to solve it? Here is my interested code areas:
my api side =>
Future changePassword(id, password) async {
try {
var prefs = await SharedPreferences.getInstance();
// User sendingData = User(
// id: id,
// );
// final dataSend = sendingData.toJson();
final response = await dio.post('http://192.168.1.108:2308/api/Account/ChangePassword',
data: jsonEncode({
"id": "$id",
"password": "$password"
}),
options: Options(headers: {
HttpHeaders.acceptHeader: '*/*',
HttpHeaders.contentTypeHeader: 'application/json',
}));
if (response.statusCode != 200) {
// debugPrint('burası-------------------------' + response.statusCode.toString());
}
prefs.remove('password');
return response;
}
catch (e) {
debugPrint(e.toString());
}
}
this is my screen side that I called it =>
onPressed: () async {
var prefs = await SharedPreferences.getInstance();
var pwd = prefs.getString('password');
var email = prefs.getString('email');
final usrId = prefs.getInt('userId');
pwdFormKey.currentState!.save();
if (pwdFormKey.currentState!
.validate()) {
try {
if(oldPwdController.text==pwd){
if(newPwdController.text==newPwdController2.text) {
await api.changePassword(usrId, newPwdController.text);
Navigator.pop(context);
Fluttertoast.showToast(
msg: "Şifreniz başarıyla değiştirilmiştir.",
toastLength: Toast
.LENGTH_SHORT,
gravity: ToastGravity
.BOTTOM,
backgroundColor: CupertinoColors
.activeGreen,
textColor: CupertinoColors
.black,
fontSize: 16.0);
}
// }
// }
else {
Fluttertoast.showToast(
msg: "Yeni girdiğiniz şifreler aynı değil, lütfen kontrol ediniz.",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: CupertinoColors.systemRed,
textColor: CupertinoColors.black,
fontSize: 16.0);
}
}
else{
Fluttertoast.showToast(
msg: "Eski Şifreniz Hatalıdır.",
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: CupertinoColors.systemRed,
textColor: CupertinoColors.black,
fontSize: 16.0);
}
} catch (e) {
return showDialog(
context: context,
builder: (BuildContext
context) {
return AlertDialog(
title: Text(
"Hatalı Deneme"),
content:
SingleChildScrollView(
child: ListBody(
children: [
Text(
"Hatalı şifre değiştirme işleminde bulundunuz. Lütfen tekrar deneyiniz.")
],
),
),
actions: [
TextButton(
child: const Text(
'Tamam'),
onPressed: () {
Navigator.of(
context)
.pop();
},
),
],
);
});
}
}
},
In post method there are 2 diff values. One is data and another one is queryParameters. You can try in this way.
Map<String, dynamic>? param = {"userName": "name"};
return await (_dio.post(
"http://192.168.1.108:2308/api/Account/ChangePassword",
data: data, //Optional
queryParameters: params,
)).catchError((e) {
if (!checkSessionExpire(e, context)) {
throw e;
}
});

Conditional statement not working correctly in Dart

By clicking on save button of the form, user either updates and existing item or add a new one. For that, in _saveForm() method, I have implemented the following if statement, but it doesn't work properly. It just updates the already-existing item and when it comes to add a new one, It does not. What is the problem?
Future<void> _saveForm() async {
final isValid = _form.currentState!.validate();
if (!isValid) {
return;
}
_form.currentState!.save();
setState(() {
_isLoading = true;
});
if (_editedItem.id != null) {
await Provider.of<Items>(context, listen: false)
.updateItem(_editedItem.id.toString(), _editedItem);
setState(() {
_isLoading = false;
});
Navigator.of(context).pop();
} else {
try {
await Provider.of<Items>(context, listen: false).addItem(_editedItem);
} catch (error) {
await showDialog(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('An error occurred!'),
content: const Text('Something went wrong.'),
actions: <Widget>[
FlatButton(
child: Text('Okay'),
onPressed: () {
Navigator.of(ctx).pop();
},
)
],
),
);
}
}
setState(() {
_isLoading = false;
});
Navigator.of(context).pop();
}
Followings are the methods called inside _saveForm() function:
Future<void> updateItem(String id, Item newItem) async {
final itemIndex = _items.indexWhere((item) => item.id == id);
if (itemIndex >= 0) {
final url = 'https://shaparak-732ff.firebaseio.com/items/$id.json';
await http.patch(Uri.parse(url),
body: json.encode({
'title': newItem.title,
'content': newItem.content,
'author': newItem.author,
'category': newItem.category,
'startColor': newItem.startColor,
'endColor': newItem.endColor,
}));
_items[itemIndex] = newItem;
notifyListeners();
} else {
print('...');
}
}
And the method that does not function:
Future<void> addItem(Item item) {
const url = 'https://shaparak-732ff.firebaseio.com/items.json';
return http
.post(
Uri.parse(url),
body: json.encode({
'title': item.title,
'content': item.content,
'author': item.author,
'category': item.category,
'startColor': item.startColor,
'endColor': item.endColor,
}),
)
.then((response) {
final newItem = Item(
title: item.title,
content: item.content,
author: item.author,
category: item.category,
startColor: item.startColor,
endColor: item.endColor,
id: json.decode(response.body)['name'],
);
_items.add(newItem);
// _items.insert(0, newProduct); // at the start of the list
notifyListeners();
});
}
I think you don't add your product id, you will follow this code .....
Future<void> addItem(Item item) {
const url = 'https://shaparak-732ff.firebaseio.com/items.json';
return http
.post(
Uri.parse(url),
body: json.encode({
'id': item.id,
'title': item.title,
'content': item.content,
'author': item.author,
'category': item.category,
'startColor': item.startColor,
'endColor': item.endColor,
}),
)
.then((response) {
final newItem = Item(
id: json.decode(response.body)['name'],
title: item.title,
content: item.content,
author: item.author,
category: item.category,
startColor: item.startColor,
endColor: item.endColor
);
_items.insert(0, newItem);
notifyListeners();
});
}
Hey basically your problem looks like it might be because id can never be null. So instead of
if (_editedItem.id != null) {
await Provider.of<Items>(context, listen: false)
.updateItem(_editedItem.id.toString(), _editedItem);
setState(() {
_isLoading = false;
});
try making it say
if (_editedItem.id != '') {
await Provider.of<Items>(context, listen: false)
.updateItem(_editedItem.id.toString(), _editedItem);
setState(() {
_isLoading = false;
});

How to display message on toast when raised button is clicked?

When login button is pressed, I want to show a toast that displays user details in successful or "not found" message otherwise.
new RaisedButton(
onPressed: () {
Future<User> user = _sendToServer();
if (user != null) {
Toast.show("You have logged as ${user.toString()}", context,
duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
} else {
Toast.show("Not found", context,
duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
}
},
child: new Text('log in'),
),
I know that I receive the right response but just unable to display it using toast.
Future<User> _sendToServer() async {
DatabaseHelper helper = DatabaseHelper.instance;
if (_key.currentState.validate()) {
// No any error in validation
_key.currentState.save();
User user = await helper.getLogin(email, password);
print("login user ${user.email}");
return user;
} else {
// validation error
setState(() {
_validate = true;
});
return null;
}
}
RaisedButton(
onPressed: () async{ // mark it async
User user = await _sendToServer(); // await to get user
if (user != null) {
Toast.show("You have logged as ${user.toString()}", context,
duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
} else {
Toast.show("Not found", context,
duration: Toast.LENGTH_SHORT, gravity: Toast.BOTTOM);
}
},
child: new Text('log in'),
)
You should make the onPressed as async and call your function with await or use it like a promise.
For exa -
yourFunctiomWithFuture().then((value) {
// Run code here
}, onError: (error) {
print(error);
});