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.
Related
i tried method using firebase_messaging: 7.0.1 but now its firebase_messaging: 14.0.2.
i got this error :
Converting object to an encodable object failed: Instance of 'Future<String?>'
sendNotif(String? title, String? body, String? id) async {
try {
await http
.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': body.toString(),
'title': title.toString()
},
'priority': 'high',
'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': id.toString(),
},
'to': FirebaseMessaging.instance.getToken(),
},
),
)
.then((value) => (value) {
print("send succeffuly");
});
} catch (e) {
print("THe ERROR : $e");
}
}
As the error message says, FirebaseMessaging.instance.getToken() returns a Future<String>, while the post API expects only current (non-Future) values.
The simplest fix is to await the value:
'to': await FirebaseMessaging.instance.getToken(),
I am trying to send a http.post request with multiple variables.
var acc = {
'acc_type': 'normal',
'time': 'Jan 27',
};
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc
},
),
);
When I remove acc: acc, Flutter sends requests. However, I need to send var acc value to the server in order to post it. I tried to encode it to JSON the http.post() function. It seems not working. How can I send the object as part of the post request?
This will work.
import 'dart:convert';
//....
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: json.encode(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc
},
),
);
var acc = {
'acc_type': 'normal',
'time': 'Jan 27',
};
var what = await http.post(
'http://localhost:7200/api/activity/addactivity',
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body:(
<String, dynamic>{
'userId': 'aaa111',
'location': 'hellooooo',
'acc': acc.toString(),
},
),
);
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()}');
}
}
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
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!