Need to post this nested structure ,
Map<String, dynamic> body = {
'amount': amount,
'currency': currency,
'description' : description,
'payment_method_types[]': 'card',
'shipping': json.encode({
'name':'some name',
'address':{
'city':'some city',
'country':'some country',
},
})
};
var response = await http.post(
StripeService.paymentApiUrl,
body: body,
headers: StripeService.headers
);
return jsonDecode(response.body);
Always getting error in Stripe logs ,
{
"error": {
"message": "Invalid object",
"param": "shipping",
"type": "invalid_request_error"
}
}
POST data from logs say ,
{
"amount": "500",
"currency": "USD",
"description": "payment for xxxx",
"payment_method_types": [
"card"
],
"shipping": "{\"name\":\"some name\",\"address\":{\"city\":\"some city\",\"country\":\"some country\"}}"
}
Have tried Map<String, String> as well .
Have you tried this:
Map<String, dynamic> body = {
'amount': amount,
'currency': currency,
'description' : description,
'payment_method_types[]': 'card',
'shipping[name]': 'some name',
'shipping[address][city]': 'some city',
'shipping[address][country]': 'some country',
};
You need to encode the body of the post model. Try this:
Map<String, dynamic> body = {
'amount': amount,
'currency': currency,
'description' : description,
'payment_method_types[]': 'card',
'shipping': {
'name':'some name',
'address':{
'city':'some city',
'country':'some country',
},
}
};
var response = await http.post(
StripeService.paymentApiUrl,
body: jsonEncode(body), // Encode only the total of post model
headers: StripeService.headers
);
Try;
: "{\"name\":\"$name\",\"address\":{\"city\":\"$city\",\"country\":\"$country\"}}"
Because I think something is wrong on encoding. follow documentation
Related
How can I save two records with the id of the other in flutter?
I'm trying to save two records with id of the other, I can do that, but when I try to save more than 2 at same time some id come with blank. This is my code:
collectionReferenceRel.add({
'idRoom': id,
'room': rel,
'rel': room,
'id': '',
}).then((idRel) {
idRel1 = idRel.id;
},
);
collectionReferenceRel.add({
'idRoom': id,
'room': room,
'rel': rel,
'id': '',
}).then((value2) {
idNode2 = value2.id;
}).whenComplete(() async {
await collectionReferenceRel.doc(idRel1).update({
'id': idRel2,
});
await collectionReferenceRel.doc(idRel2).update({
'id': idRel1,
});
}).catchError((error) {
CustomFullScreenDialog.cancelDialog();
CustomSnackBar.showSnackBar(
context: Get.context,
title: 'Error',
message: 'Something went wrong',
backgroundColor: Colors.green);
[![enter image description here][1]][1] },
);
https://api.flutter-io.cn/flutter/dart-async/Future/wait.html
Future.wait([
collectionReferenceRel.add({
'idRoom': id,
'room': rel,
'rel': room,
'id': '',
}).then((idRel) {
idRel1 = idRel.id;
},
),
collectionReferenceRel.add({
'idRoom': id,
'room': room,
'rel': rel,
'id': '',
}).then((value2) {
idNode2 = value2.id;
})
]).whenComplete(() async {
await collectionReferenceRel.doc(idRel1).update({
'id': idRel2,
});
await collectionReferenceRel.doc(idRel2).update({
'id': idRel1,
});
}).catchError((error) {
CustomFullScreenDialog.cancelDialog();
CustomSnackBar.showSnackBar(
context: Get.context,
title: 'Error',
message: 'Something went wrong',
backgroundColor: Colors.green);
[![enter image description here][1]][1] },
);
Consider using the set() method provided the cloud firestore api.
Usage Example from the reference.
final city = <String, String>{
"name": "Los Angeles",
"state": "CA",
"country": "USA"
};
db.collection("cities")
.doc("LA")
.set(city)
.onError((e, _) => print("Error writing document: $e"));
For saving more than one document consider coupling it with the Future wait for a clean code.
/// Create a list to add all documents
final List docs = [];
/// create the documents with unique identifiers
/// beforehand using a package such as `Uuid`
final docA = {
'id': 'unique_identifier_a',
'idRoom': id,
'room': rel,
'rel': room,
}
docs.add(docA);
final docB = {
'id': 'unique_identifier_b',
'idRoom': id,
'room': rel,
'rel': room,
}
docs.add(docB);
/// Create futures from the documents
final futures = docs.map((e) => collectionRef.doc(e.id).set(e));
/// Save the documents in shot and wait for all
await Future.wait(futures);
I have a JSON object here:
{
"data": [
{
"id": 1,
"countryName": "India"
},
{
"id": 2,
"countryName": "USA"
}
],
"exceptionInfo": null,
"message": null,
"messages": null,
"isSuccess": true
}
I want to fetch the name parameter under data to a DropDownMenuList. I have a data model here:
import 'dart:convert';
GetCountry getCountryFromJson(String str) => GetCountry.fromJson(json.decode(str));
String getCountryToJson(GetCountry data) => json.encode(data.toJson());
class GetCountry {
GetCountry({
this.data,
this.exceptionInfo,
this.message,
this.messages,
this.isSuccess,
});
List<CountryModal> data;
dynamic exceptionInfo;
dynamic message;
dynamic messages;
bool isSuccess;
factory GetCountry.fromJson(Map<String, dynamic> json) => GetCountry(
data: List<CountryModal>.from(json["data"].map((x) => CountryModal.fromJson(x))),
exceptionInfo: json["exceptionInfo"],
message: json["message"],
messages: json["messages"],
isSuccess: json["isSuccess"],
);
Map<String, dynamic> toJson() => {
"data": List<dynamic>.from(data.map((x) => x.toJson())),
"exceptionInfo": exceptionInfo,
"message": message,
"messages": messages,
"isSuccess": isSuccess,
};
}
class CountryModal {
CountryModal({
this.id,
this.countryName,
});
int id;
String countryName;
factory CountryModal.fromJson(Map<String, dynamic> json) => CountryModal(
id: json["id"],
countryName: json["countryName"],
);
Map<String, dynamic> toJson() => {
"id": id,
"countryName": countryName,
};
}
The function to fetch the data is below and is the indifferent file:
Future<GetCountry> Getcountry(String authToken) async{
try {
String uriParts = apiEndPoint.getUriParts('location/GetCountries');
var response = await http.get(
apiEndPoint.getHTTPUri(uriParts),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': authToken
},
);
var responseJson = jsonDecode(response.body);
GetCountry country = GetCountry.fromJson(responseJson);
return country;
}
catch (err) {
debugPrint(err.toString());
throw err;
}
}
This method fetches the item successfully into a ListView.builder widget but I am a bit lost on how to fetch this to a List<DropdownMenuItem> items.
I have tried going through solutions but nothing seems to work for me.
please help.
EDIT:-
Below is the code for the dropdown list -:
List<CountryModal> _countrylist = [];
String mycountry;
DropdownButton(
items: _countrylist.map((item) {
return new DropdownMenuItem(
child: new Text(
item.countryName,
style: TextStyle(fontSize: 14.0),
),
value: item.id.toString(),
);
}).toList(),
hint: Text(
"Please select the country",
style: TextStyle(
color: Colors.black45,
),),
onChanged: (newVal) {
setState(() {
mycountry = newVal;
});
},
value: mycountry,
),
Error message below -:
Sample json format -:
{
"error": "0",
"message": "Succesfully fetched",
"status": true,
"data": [
{
"id": "5df0b94841f0331baf1357bb",
"stateName": "test group",
},
{
"id": "5df0df507091683d2f1ad0cf",
"stateName": "new group",
}
]
}
You will just pass a map.toList() to the items field.
DropdownButton(items: myGetCountry.map((CountryModal e) {
return DropdownMenuItem(child: SomeWidget(e))).toList();
})
Flutter rest API showing 'Required parameter missing or invalid'
main() async {
final data = {
'customer': {
'first_name': 'Karla',
'last_name': 'Mullins',
'email': 'KarlaMullins#mailinator.com',
'phone': '+15142546011',
'verified_email': true,
'addresses': [
{
'address1': '123 Oak St1',
'city': 'Ottawa1',
'province': 'ON',
'phone': '555-1212',
'zip': '123 ABC',
'last_name': 'Mullins',
'first_name': 'Karla',
'country': 'CA',
}
]
}
};
var json = jsonEncode(data);
String username = 'u';
String password = 'p';
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
var response = await http.post(url',
headers: <String, String>{
'authorization': basicAuth,
"Accept": "application/json",
},
body: json,
);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
calling rest api with basic authorisation from flutter dart showing Response status: 400
and Response body: {"errors":{"customer":"Required parameter missing or invalid"}}.
Change Accept into "content-type":"application/x-www-form-urlencoded
Or application/json, depending on your api.
I am using stripe sdk for payment and trying to create customer in that ,
static Future<Map<String, dynamic>> createcustomer() async {
try {
var body = {
'name': 'Jenny Rosen',
'address': {
'line1': '510 Townsend St',
'postal_code': '98140',
'city': 'San Francisco',
'state': 'CA',
'country': 'US',
}
};
var response = await http.post(
'https://api.stripe.com/v1/customers',
body: json.encode(body),
headers: StripeService.headers
);
print('resvfdg: ${jsonDecode(response.body)}');
return jsonDecode(response.body);
} catch (err) {
print('err charging user: ${err.toString()}');
}
return null;
}
i am getting the error code: parameter_unknown,message: Received unknown parameter ,
how to create customer in stripe ?? or what i am missing in this ?
i don't know how to apply this and i need to create customer for doing international payment outside india , if i done payment in "INR" it will working properly , but for any other currency they asked for name and address.
I'm using Dio, this code is working for me:
static Future<Map<String, dynamic>> createcustomer() async {
try {
var data = {
'name': 'Jenny Rosen',
'address': {
'line1': '510 Townsend St',
'postal_code': '98140',
'city': 'San Francisco',
'state': 'CA',
'country': 'US',
}
};
Response response = await Dio().post('https://api.stripe.com/v1/customers',
data: data,
options: Options(contentType:Headers.formUrlEncodedContentType,
headers: {
'Authorization': 'Bearer ${secret}', // your secret key
}
),
);
print('response: ${jsonDecode(response.data)}');
return jsonDecode(response.data);
} catch (err) {
print('err charging user: ${err.toString()}');
}
return null;
}
I have used this api is working fine but response is paramter unknown
{error: {code: parameter_unknown, doc_url: https://stripe.com/docs/error-codes/parameter-unknown, message: Received unknown parameter: {"address":"sss","email":"aryan#gmail.com","name":"aryan","phone":"953667"}, param: {"address":"sss","email":"aryan#gmail.com","name":"aryan","phone":"953667"}, type: invalid_request_error}}
Flutter Code
Future createcustomer() async {
try {
var body = {
"address": "sss",
"email": "aryan#gmail.com",
"name": "aryan",
"phone": "95366710",
};
//final response = await http.post(Uri.parse("https://api.stripe.com/v1/customers"),
final response = await http.post(Uri.parse("https://api.stripe.com/v1/customers"),
headers: {
"Content-Type": "application/x-www-form-urlencoded","Authorization": "Bearer ${sKey}",
},
body: json.encode(body),
);
print('resvfdg: ${jsonDecode(response.body)}');
return jsonDecode(response.body);
} catch (err) {
print('err charging user: ${err.toString()}');
}
}
I'm implementing a payment gateway in my flutter application. So Razorpay recommends me to use Orders API. But I don't get any ways to implement Orders API.
I had referred the below documentation. It contains examples for java, PHP, etc. But nothing found for Flutter / Dart.
https://razorpay.com/docs/payment-gateway/orders/integration/#example
Thanks in advance.
Future<void> generate_ODID() async {
var orderOptions = {
'amount': 50000, // amount in the smallest currency unit
'currency': "INR",
'receipt': "order_rcptid_11"
};
final client = HttpClient();
final request =
await client.postUrl(Uri.parse('https://api.razorpay.com/v1/orders'));
request.headers.set(
HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
String basicAuth = 'Basic ' +
base64Encode(utf8.encode(
'${'YourKEY'}:${'YourSECRET'}'));
request.headers.set(HttpHeaders.authorizationHeader, basicAuth);
request.add(utf8.encode(json.encode(orderOptions)));
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
print('ORDERID'+contents);
String orderId = contents.split(',')[0].split(":")[1];
orderId = orderId.substring(1, orderId.length - 1);
Fluttertoast.showToast(
msg: "ORDERID: " +orderId,
toastLength: Toast.LENGTH_SHORT);
Map<String, dynamic> checkoutOptions = {
'key': 'YourKEY',
'amount': 11100,
'name': 'Demo',
'description': 'Fssai Registrtion Charge',
'prefill': {'contact': '8910407549', 'email': 'xx.xx#gmail.com'},
'external': {
'wallets': ['paytm']
}
};
try {
_razorpay.open(checkoutOptions);
} catch (e) {
print(e.toString());
}
});
}
I am using this same code snippet but when I am trying to do payments with google pay then it will fail with "Your money is not debited, Your server is busy" Error, but when I try to do with providing UPI Id manually then the transaction goes smoothly, otherwise transactions not done using UPI. Is there any way to solve this?
final client = HttpClient();
final request =
await client.postUrl(Uri.parse('https://api.razorpay.com/v1/orders'));
request.headers.set(
HttpHeaders.contentTypeHeader, "application/json; charset=UTF-8");
String basicAuth = 'Basic ' +
base64Encode(utf8.encode(
'${dotenv.env['RAZORPAY_KEY']!}:${dotenv.env['RAZORPAY_SECRET']!}'));
request.headers.set(HttpHeaders.authorizationHeader, basicAuth);
request.add(utf8.encode(json.encode(orderOptions)));
final response = await request.close();
response.transform(utf8.decoder).listen((contents) {
String orderId = contents.split(',')[0].split(":")[1];
orderId = orderId.substring(1, orderId.length - 1);
Map<String, dynamic> checkoutOptions = {
'key': dotenv.env['RAZORPAY_KEY']!,
'amount': total * 100,
"currency": "INR",
'name': 'E Drives',
'description': 'E Bike',
'order_id': orderId, // Generate order_id using Orders API
'timeout': 300,
};
try {
_razorpay.open(checkoutOptions);
} catch (e) {
log.e(e.toString());
}
You can use HttpClient and send a request to the Razorpay Orders API.
Hope this answers your question.
Thankfully, Razorpay has Flutter package which you can use. The following code snippet might help :
import 'package:razorpay_flutter/razorpay_flutter.dart';
_razorpay = Razorpay();
var options = {
'key': '<YOUR_KEY_ID>',
'amount': 100, //in the smallest currency sub-unit.
'name': 'Acme Corp.',
'order_id': 'order_EMBFqjDHEEn80l', // Generate order_id using Orders API
'description': 'Fine T-Shirt',
'prefill': {
'contact': '9123456789',
'email': 'gaurav.kumar#example.com'
}
};
_razorpay.open(options);
Please go through this page for further details. And this YouTube video will help as well.
You can use the Below code. it's working as expected.
createOrderId(amount, description, id, userId) async {
final int Amount = int.parse(amount) * 100;
http.Response response = await http.post(
Uri.parse(
"https://api.razorpay.com/v1/orders",
),
headers: {
"Content-Type": "application/json",
"Authorization":
"Basic ${base64Encode(utf8.encode('testKey:secreateKey'))} "
},
body: json.encode({
"amount": Amount,
"currency": "INR",
"receipt": "OrderId_$id",
"notes": {"userId": "$userId", "packageId": "$id"},
}));
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
openCheckout(amount, description, id, userId, data["id"]);
}
print(response.body);
}
void openCheckout(amount, description, id, userId, String orderId) async {
final int Amount = int.parse(amount) * 100;
var options = {
'key': 'testkey',
'amount': Amount,
'name': 'Name',
'description': description,
'order_id': orderId,
// "prefill": {
// "name": name,
// "email": emails,
// },
"notes": {"userId": "$userId", "packageId": "$id"},
'external': {
'wallets': ['paytm']
}
};
try {
_razorpay.open(options);
} catch (e) {
debugPrint('Error: e');
}
}
Might be helpful for someone.
Hope you set up all the necessary things.
Step 1: creating Order using Razorpay official Order Api:
//* create order##############################################################
void createOrder() async {
String username = 'xxxxxxxxxx';// razorpay pay key
String password = "xxxxxxxxxxxxxxxx";// razoepay secret key
String basicAuth =
'Basic ${base64Encode(utf8.encode('$username:$password'))}';
Map<String, dynamic> body = {
"amount": 1 * 100,
"currency": "INR",
"receipt": "rcptid_11"
};
var res = await http.post(
Uri.https(
"api.razorpay.com", "v1/orders"), //https://api.razorpay.com/v1/orders // Api provided by Razorpay Official 💙
headers: <String, String>{
"Content-Type": "application/json",
'authorization': basicAuth,
},
body: jsonEncode(body),
);
if (res.statusCode == 200) {
openCheckout(jsonDecode(res.body)['id']); // 😎🔥
}
print(res.body);
}
//*#################################################################
Step 2: Open Razorpay checkout interface.
After getting orderId from Razorpay official Api, pass the id when calling openCheckout(jsonDecode(res.body)['id']); function
void openCheckout(String orderId) async {
var options = {
'key': 'xxxxxxxxxxxxxxxx',
"amount": 1 * 100,
'order_id': orderId,
'name': 'main.co.in',
// 'prefill': {'contact': '', 'email': 'test#razorpay.com'},
'external': {
'wallets': ['paytm']
}
};
try {
razorpay.open(options);
} catch (e) {
debugPrint('Error: e');
}
}
3rd Step: Signature verification.
This is important if you automatically wanna transfer your amount to your bank account.
for Hmac SHA key , install this package: crypto:
handlerPaymentSuccess(PaymentSuccessResponse response) {
final key = utf8.encode('NgDLPyiDRPuQpcXy1E3GKTDv');
final bytes = utf8.encode('${response.orderId}|${response.paymentId}');
final hmacSha256 = Hmac(sha256, key);
final generatedSignature = hmacSha256.convert(bytes);
if (generatedSignature.toString() == response.signature) {
log("Payment was successful!");
//Handle what to do after a successful payment.
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Success : payment successful"),
// content: const Text("Are you sure you wish to delete this item?"),
actions: <Widget>[
ElevatedButton(
onPressed: () {
Navigator.of(context).pop(true);
// PlaceOrderPrepaid();
},
child: Text("OK"))
// ),
],
);
},
);
} else {
log("The payment was unauthentic!");
}
}
Thats it!