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, );
}
}
Related
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, );
}
}
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));
}
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;
}
});
I'm trying to test a payment gateway method with stripe and I have this error when i try to click the button which it said "[log] {success: false, error: o is not defined}", here is my code. I'm not sure what or how to solve this but I would really need some help on this one. Also I included with the screenshot of the problem
Main.dart
import 'dart:convert';
import 'dart:developer';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'package:http/http.dart' as http;
Future <void> main() async{
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(
options: FirebaseOptions(apiKey: "AIzaSyD7Uhhiv85NCcDjoTEQ-K7T5qU4bNXci8M",
appId: "XXX", messagingSenderId: "XXX",
projectId: "itt632-56973",
));
Stripe.publishableKey = "pk_test_51LHIjvJ5bt4B4CmJ3xTspeufDqv4VojZlmhuBaVvjhUoDbJaoKziiUkFZPOTl3a4CbVcfdmnJKosItZiiweRYfvF00aOI2xKIS";
Stripe.instance.applySettings();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Demo(),
);
}
}
// 'https://us-central1-itt632-56973.cloudfunctions.net/stripePaymentIntentRequest'),
class Demo extends StatelessWidget {
const Demo({Key? key}) : super(key: key);
Future<void> initPayment(
{required String email,
required double amount,
required BuildContext context}) async {
try {
// 1. Create a payment intent on the server
final response = await http.post(
Uri.parse(
'https://us-central1-itt632-56973.cloudfunctions.net/stripePaymentIntentRequest'),
body: {
'email': email,
'amount': amount.toString(),
});
final jsonResponse = jsonDecode(response.body);
log(jsonResponse.toString());
// 2. Initialize the payment sheet
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: jsonResponse['paymentIntent'],
merchantDisplayName: 'Grocery Flutter course',
customerId: jsonResponse['customer'],
customerEphemeralKeySecret: jsonResponse['ephemeralKey'],
testEnv: true,
merchantCountryCode: 'SG',
));
await Stripe.instance.presentPaymentSheet();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Payment is successful'),
),
);
} catch (errorr) {
if (errorr is StripeException) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('An error occured ${errorr.error.localizedMessage}'),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('An error occured $errorr'),
),
);
}
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
child: const Text('Pay 50\$'),
onPressed: () async {
await initPayment(
amount: 50.0, context: context, email: 'JEFRILUQMAN#test.com');
},
)),
);
}
}
Here is the index.js function for the stripe
const functions = require("firebase-functions");
const stripe = require("stripe")("sk_test_51LHIjvJ5bt4B4CmJclvzNcSaSPICuutFIjmg3GZb1sv6fySDehLAhvHOW2hl1W7EWXYM5oqfHkHZyJDeB36rIJpf00ksfQJnWa");
exports.stripePaymentIntentRequest = functions.https.onRequest(async (req, res) => {
try {
let customerId;
//Gets the customer who's email id matches the one sent by the client
const customerList = await stripe.customers.list({
email: req.body.email,
limit: 1
});
//Checks the if the customer exists, if not creates a new customer
if (customerList.data.length !== 0) {
customerId = customerList.data[0].id;
}
else {
const customer = await stripe.customers.create({
email: req.body.email
});
customerId = customer.data.id;
}
//Creates a temporary secret key linked with the customer
const ephemeralKey = await stripe.ephemeralKeys.create(
{ customer: customerId },
{ apiVersion: '2020-08-27' }
);
//Creates a new payment intent with amount passed in from the client
const paymentIntent = await stripe.paymentIntents.create({
amount: parseInt(req.body.amount),
currency: 'usd',
customer: customerId,
})
res.status(200).send({
paymentIntent: paymentIntent.client_secret,
ephemeralKey: ephemeralKey.secret,
customer: customerId,
success: true,
})
} catch (error) {
res.status(404).send({ success: false, error: error.message })
}
});
Screenshot
Screenshot2
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;
});