how to put the user id in this code when I am generating a to-do list and i need to retrieve the tasks that a certain user?
Future<void> create(String todo, String description) async {
try {
await firestore.collection("Todo").add({
'todo': todo,
'description': description,
'timestamp': FieldValue.serverTimestamp()
});
} catch (e) {
print(e);
}
}
i solved my issue
Future<void> create(String todo, String description) async {
String? Uid= FirebaseAuth.instance.currentUser!.uid;
print(Uid);
print(FirebaseAuth.instance.currentUser!.uid);
try {
await firestore
.collection("TodoList")
.doc(Uid)
.collection("Todo")
.add({
'todo': todo,
'description': description,
'timestamp': FieldValue.serverTimestamp()
});
} catch (e) {
print(e);
}
}
Future<void> signUpController(email, password, username, phone) async {
print("$email,$password,$username,$phone");
try {
CommanDialog.showLoading();
final credential =
await FirebaseAuth.instance.createUserWithEmailAndPassword(
email: email.trim(),
password: password,
);
print(credential);
CommanDialog.hideLoading();
try {
CommanDialog.showLoading();
var response =
await FirebaseFirestore.instance.collection('userlist').add({
'user_id': credential.user!.uid,
'user_name': username,
'phone': phone,
'password': password,
'joindate': DateTime.now().millisecondsSinceEpoch,
'email': email
});
print("response:: ${response.toString()}");
CommanDialog.hideLoading();
Get.back();
} catch (execption) {
CommanDialog.hideLoading();
print("error saving data ${execption}");
}
Get.back();
} on FirebaseAuthException catch (e) {
CommanDialog.hideLoading();
if (e.code == 'weak-password') {
CommanDialog.showErrorDialog(
description: "The password provided is too weak.");
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
CommanDialog.showErrorDialog(
description: "The account already exists for that email.");
print('The account already exists for that email.');
}
} catch (e) {
CommanDialog.hideLoading();
CommanDialog.showErrorDialog(description: "something went wrong");
print(e);
}
}
Related
I'm trying to create an auth service and I want to return the verificationId from the custom method. However, calling this method throws the null check exception because it doesn't wait for the Future to complete before returning.
Future<String> sendPhoneVerification({
required String phoneNumber,
}) async {
String? result;
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: '+1$phoneNumber',
verificationCompleted: (
PhoneAuthCredential credential,
) {
result = credential.verificationId;
},
verificationFailed: (e) {
if (e.code == 'invalid-phone-number') {
throw InvalidPhoneNumberAuthException();
} else if (e.code == 'too-many-requests') {
throw TooManyRequestsAuthException();
} else {
throw GenericAuthException();
}
},
codeSent: (verificationId, resendToken) {
print('ver_id $verificationId');
result = verificationId;
},
codeAutoRetrievalTimeout: (_) {},
);
print('This is the result $result');
return result!;
}
Here is the output in the terminal.
flutter: This is the result null
flutter: ver_id <ver_id>
Please add this property timeout: const Duration(seconds: 60), in the verifyPhoneNumber() method
I figured out the solution. I found out the verifyPhoneNumber method returns a future but the implementation doesn't await that async call. I used a [completer][1] to return a future.
Future<String> sendPhoneVerification({required String phoneNumber}) async {
Completer<String> result = Completer();
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: '+1$phoneNumber',
verificationCompleted: (
PhoneAuthCredential credential,
) {
result.complete(credential.verificationId);
},
verificationFailed: (e) {
if (e.code == 'invalid-phone-number') {
result.completeError(InvalidPhoneNumberAuthException());
} else if (e.code == 'too-many-requests') {
result.completeError(TooManyRequestsAuthException());
} else {
result.completeError(GenericAuthException());
}
},
codeSent: (verificationId, resendToken) {
result.complete(verificationId);
},
codeAutoRetrievalTimeout: (_) {},
);
return result.future;
}
i wanted to wait till firebase auth retrive verification_id and then return function
but in current code variable value newVerificationId is getting return first as error without updating from firebase
Future<String> phoneAuthontication(
phoneNumberController,
) async {
String newVerificationId = "error";
try {
await auth.verifyPhoneNumber(
phoneNumber: phoneNumberController.text,
verificationCompleted: (_) {},
verificationFailed: (e) {
print(e);
},
codeSent: (String verificationId, int? token) {
print("====" + verificationId);
newVerificationId = verificationId;
},
codeAutoRetrievalTimeout: (e) {
print(e);
});
} catch (e) {
print(e);
}
print("---" + newVerificationId);
return newVerificationId;
}
I am trying to have access to notificationId once it gets created however the delete function deletes all the documents under this collection ('user-notifications').
Do you know what I need to change so I can remove only one document rather than all documents in this collection?
Future<String> likeAnnouncementNotification(String announcementId,
String imageUrl, String ownerUid, String uid, List liked) async {
String notificationid = const Uuid().v1();
String res = "Some error occurred";
try {
if (liked.contains(uid)) {
FirebaseFirestore.instance
.collection('notifications')
.doc(ownerUid)
.collection('user-notifications')
.where("uid", isEqualTo: FirebaseAuth.instance.currentUser?.uid)
.get()
.then((value) {
value.docs.forEach((document) {
document.reference.delete();
});
});
} else {
FirebaseFirestore.instance
.collection('notifications')
.doc(ownerUid)
.collection('user-notifications')
.doc(notificationid)
.set(
{
'imageUrl': imageUrl,
'announcementId': announcementId,
'notificationid': notificationid,
'timestamp': DateTime.now(),
'type': 0,
'uid': uid
},
);
}
res = 'success';
} catch (err) {
res = err.toString();
}
return res;
}
the only thing i see that you need to specify what notification document you went to delete add it like parameter when you call likeAnnouncementNotification function
Future<String> likeAnnouncementNotification(
String announcementId,
String imageUrl,
String ownerUid,
String uid,
List liked,
) async {
String notificationid = const Uuid().v1();
String res = "Some error occurred";
try {
if (liked.contains(uid)) {
FirebaseFirestore.instance
.collection('notifications')
.doc(ownerUid)
.collection('user-notifications')
.where("uid", isEqualTo: FirebaseAuth.instance.currentUser?.uid)
.get()
.then((value) {
value.docs.forEach((notification) {
FirebaseFirestore.instance
.collection('notifications')
.doc(ownerUid)
.collection('user-notifications')
.doc(notification.id) // this is the problem you need to specify what notification document you went to delete.
.delete();
});
});
} else {
FirebaseFirestore.instance
.collection('notifications')
.doc(ownerUid)
.collection('user-notifications')
.doc(notificationid)
.set(
{
'imageUrl': imageUrl,
'announcementId': announcementId,
'notificationid': notificationid,
'timestamp': DateTime.now(),
'type': 0,
'uid': uid
},
);
}
res = 'success';
} catch (err) {
res = err.toString();
}
return res;
}
I am unable to store data in cloud firestore. Authentication is all correct but the data is not going in cloud firestore and because of that login also not working because cloud firestore is pre-req to login function
That's my AuthContoller function
storeUserData({name, password, email}) async {
DocumentReference store = firestore
.collection("users")
.doc(FirebaseAuth.instance.currentUser!.uid);
store.set(
{'name': name, 'password': password, 'email': email, 'imageUrl': ''});
}
and that's my signup button code
try {
await controller
.signupMethod(
context: context,
email: emailController.text,
password: passwordController.text,
)
.then((value) {
** return controller
.storeUserData(
email: emailController.text,
name: nameController.text,
password: passwordController.text)
.then((value) {
VxToast.show(context,
msg: 'Account Created Sucessfully');
Get.offAll(LoginScreen());
}); **
});
} catch (e) {
FirebaseAuth.instance.signOut();
VxToast.show(context, msg: e.toString());
}
try this
storeUserData({name, password, email}) async {
final _firestore = FirebaseFirestore.instance;
await _firestore.collection("users")
.doc(FirebaseAuth.instance.currentUser!.uid).set(
{'name': name, 'password': password, 'email': email, 'imageUrl': ''});
}
I'm trying to use flutter_stripe for a stripe connect account, But I always get the
same error: The client_secret provided doesn't match the client_secret associated with the PaymentIntend.
I've completed all steps according to flutter_stripe but I still face this error.
Below is my code Please check this and help me.
inde.js
const functions = require("firebase-functions");
const stripe = require("stripe")("secret_key");
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({
clientSecret: paymentIntent.client_secret,
paymentIntent: paymentIntent,
ephemeralKey: ephemeralKey.secret,
customer: customerId,
success: true,
})
} catch (error) {
res.status(404).send({ success: false, error: error.message })
}
});
PaymentService.dart
Future<void> initPaymentSheet(
{required BuildContext context, required String email, required int amount}) async {
try {
// 1. create payment intent on the server
final response = await http.post(
Uri.parse(
'Firebase api link of Functions'),
body: {
'email': email,
'amount': amount.toString(),
});
Map<String, dynamic> paymentIntentBody = jsonDecode(response.body);
log(paymentIntentBody.toString());
//2. initialize the payment sheet
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentBody["clientSecret"],
merchantDisplayName: 'Flutter Stripe Store Demo',
customerId: paymentIntentBody['customer'],
customerEphemeralKeySecret: paymentIntentBody['ephemeralKey'],
style: ThemeMode.light,
testEnv: true,
merchantCountryCode: 'US',
),
);
await Stripe.instance.presentPaymentSheet();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Payment completed!')),
);
} catch (e) {
if (e is StripeException) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Error from Stripe: ${e.error.localizedMessage}'),
),
);
} else {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Error the Stripe of : $e')),
);
}
}
}
The log error print on my console is :
> [log] {paymentIntent:
> pi_3LI2acCTAUDjRNFV1Ra3dahz_secret_Fcqw73pWrE4avKRyuDVzRBitG,
> ephemeralKey:
> ek_test_YWNjdF8xSlQ3amtDVEFVRGpSTkZWLDl1OE5Vdm1jTGY4T1RpaVhHOTB3NTRVSkQ5UGl4azA_00j32OYG9n,
> customer: cus_LHG2YpQP9Cgwuy, success: true}
The following code is from a previous Stripe evaluation stage. But it worked. Slim it down to your needs.
Remember to publish your secret key to the server, so the server can talk to Stripe.
code.dart
Future<bool> payWithPaymentSheet(
ProductModel productModel, PriceModel priceModel,
{String merchantCountryCode = 'DE'}) async {
if (kIsWeb) {
throw 'Implementation not availabe on Flutter-WEB!';
}
String uid = AuthService.instance.currentUser().uid;
String email = AuthService.instance.currentUser().email ?? '';
HttpsCallableResult response;
try {
response = await FirebaseFunctions
.httpsCallable('createPaymentIntent')
.call(<String, dynamic>{
'amount': priceModel.unitAmount,
'currency': priceModel.currency,
'receipt_email': email,
'metadata': {
'product_id': productModel.id,
'user_id': uid,
"valid_until": productModel.getUntilDateTime().toIso8601String(),
'product_name': productModel.name.tr,
},
'testEnv': kDebugMode,
});
} on FirebaseFunctionsException catch (error) {
log(error.code);
log(error.details);
log(error.message ?? '(no message)');
Get.snackbar(
error.code,
error.message ?? '(no message)',
icon: const Icon(Icons.error_outline),
);
return false;
}
Map<String, dynamic> paymentIntentBody = response.data;
await Stripe.instance.initPaymentSheet(
paymentSheetParameters: SetupPaymentSheetParameters(
paymentIntentClientSecret: paymentIntentBody["clientSecret"],
currencyCode: priceModel.currency,
applePay: false,
googlePay: false,
merchantCountryCode: merchantCountryCode,
merchantDisplayName: Strings.appName,
testEnv: kDebugMode,
customerId: paymentIntentBody['customer'],
customerEphemeralKeySecret: paymentIntentBody['ephemeralKey'],
));
try {
await Stripe.instance.presentPaymentSheet();
return true;
} on StripeException catch (e) {
log(e.error.code.name);
log(e.error.message ?? '(no message)');
log(e.error.localizedMessage ?? '(no message)');
Get.snackbar(e.error.code.name, e.error.message ?? '',
icon: const Icon(Icons.error_outline));
} catch (e) {
Get.snackbar('An unforseen error occured', e.toString(),
icon: const Icon(Icons.error_outline));
}
return false;
}
index.ts
// SETTING SECRET KEY ON SERVER:
// cd functions
// firebase functions:config:set stripe.secret_key="sk_live_51L...Noe"
// firebase deploy --only functions
let stripe = require("stripe")(functions.config().stripe.secret_key);
exports.createPaymentIntent = functions
.https.onCall((data, context) => {
// if (!context.auth) {
// return { "access": false };
// }
return new Promise(function (resolve, reject) {
stripe.paymentIntents.create({
amount: data.amount,
currency: data.currency,
receipt_email: decodeURIComponent(data.receipt_email),
metadata: data.metadata,
}, function (err, paymentIntent) {
if (err != null) {
functions.logger.error("Error paymentIntent: ", err);
reject(err);
}
else {
resolve({
clientSecret: paymentIntent.client_secret,
paymentIntentData: paymentIntent,
});
}
});
});
});