I'm new to flutter technology and trying to learn to work with API, the confusion I'm having is that when I look down and study the stripe documentation for payment or any other API, it is accepting everything as a parameter but in my code, I'm passing the body that is required by stripe as a parameter and it works fine, so I am confused why does it work fine while the stripe API wants the data as parameters
Below is the code I've written so please anyone help me understand this,
is this because of the content type I am providing or what?
Please Clarify me,
Thanks
Map<String, dynamic> body = {
'amount': amountInUSDCents.toString(),
'currency': currency,
'payment_method_types[]': 'card',
'receipt_email': widget.email,
};
Uri url = Uri.parse('https://api.stripe.com/v1/payment_intents');
var response = await http.post(url, headers: {
'Authorization':
'Bearer secret key here',
'Content-Type': 'application/x-www-form-urlencoded'
});
Related
If return 401 (Unauthorized), I don't know password field is wrong or username is wrong in frontend.
Which code should return for password wrong? and which code for username wrong?
I wanna know exactly which field is wrong in authentication.
Usually to identify what happened in backend we send a HTTP code along with some kind of data/message in the body.
You can simply print parameters value which you send to the Api for better understanding which you send and which response you get. And please make a validation in Email and Password TextFormField because when email and password pattern perfect that after you can send a post request to the backend so you get less error.
Code for parameter printing:
Future<http.Response> createUser(String email, String password) {
//Print parameters here for better understanding:
print('params===>{$email && $password}');
return http.post(
Uri.parse('https://reqres.in/api/users'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{'name': email, 'job': password}),
);
}
I'm trying to call an api from flutter but i keep getting 401 Unauthorized. According to the api documentation it uses basic authentiocation and is UTF-8 encoded. The username and password is provided by the docs and if try the api in a web browser and enter those credentials it goes through and i recieve the data. This is the code i'm using in flutter:
Future<void> requestData() async {
String username = 'abc';
String password = '123';
String basicAuth = 'Basic ' + base64Encode(utf8.encode('$username:$password'));
Response r = await get(
Uri.parse('http://api.example.com'),
headers: {
HttpHeaders.authorizationHeader: basicAuth,
});
print(r.body);
print(r.statusCode);
}
I've also tried this variation which gave the same result:
headers: <String, String>{
'authorization': basicAuth
}
Seeing as the username and password are correct there must be something wrong with how i make the call, but i've tried to do it a bunch of different ways and nothing works. Any help would be greatly appreciated!
As per my experience, there is no need of token or basic auth while doing login. And login is post method not get.
Turns out the documentation i read was outdated/incorrect. The api uses "Digest authentication" which i looked up and was able to implement. This is the code if anyone is interested:
import 'package:http/http.dart';
import 'package:http_auth/http_auth.dart';
...
Response res = await DigestAuthClient("USERNAME", "PASSWORD")
.get(Uri.parse("API_URL")).timeout(const Duration(seconds: 20));
I am trying to use the sales force api. But I keep getting a CORS error. Some try to help by directing me to a solution for a web app that does not work. For example, one link I was directed to says to add the domain to an "allowed" list. But I am not coming from a domain, at least not in any way that I know of. Do all cell phones belong in a domain? Does each phone have its own domain? Or is the solution inapplicable.
Another solution I was criticized for duplication said to use "Access-Control-Request-Method" as described in this post I was directed to. But the first problem is that I had to convert everything from web pass to mobile pass. I have no idea if I did it right. The second problem is that it still fails with no new information. A third problem is the link has absolutely no information what value gets assigned to "Access-Control-Request-Method" I tried various guesses but to no avail.
I have ran out of things to guess!
void getData() async {
var headers = {
'Authorization': 'Bearer access_token',
'Access-Control-Allow-Origin': 'https://instance-name.salesforce.com/',
'Access-Control-Allow-Methods': 'POST, GET',
'Access-Control-Allow-Headers': 'Content-Type, application/json',
};
var res = await http.get(
'https://instance-name.com/services/data/v20.0/',
headers: headers);
if (res.statusCode != 200)
throw Exception('http.get error: statusCode= ${res.statusCode}');
print(res.body);
}
You can use third party service to avoid CORS policy issue. There are several services available online. You can try https://allorigins.win/ and its works fine. Try following code
void getData() async {
var headers = {
'Authorization': 'Bearer access_token',
'Access-Control-Allow-Origin': 'https://instance-name.salesforce.com/',
'Access-Control-Allow-Methods': 'POST, GET',
'Access-Control-Allow-Headers': 'Content-Type, application/json',
};
var res = await http.get(
'https://api.allorigins.win/raw?url=https://instance-name.com/services/data/v20.0',
headers: headers);
if (res.statusCode != 200)
throw Exception('http.get error: statusCode= ${res.statusCode}');
print(res.body);
}
I`m trying to get the token from the spotify API, I use axios. I use the example given by the API as a guide, but give me the error 404
export const getToken = code => async dispatch => {
const responseToken = await axios.post({
url: "https://accounts.spotify.com/api/token",
form: {
grant_type: "authorization_code",
code,
redirect_uri
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
json: true
})
console.log(responseToken);
The first line is because I`m using redux,I just wanted you to see that it was a asinc method.
I have being all day trying to fix this, I don`t have more ideas of how to solve this
Try changing
form: {
grant_type: "authorization_code",
code,
redirect_uri
}
to
data: JSON.stringify({
grant_type: "authorization_code",
code,
redirect_uri
})
You want to send it in the request body, hence "data", that's how you define it in axios.
Also, I don't think you need json: true
EDIT:
Pretty sure you have to add 'content-type': 'application/x-www-form-urlencoded;charset=utf-8' to the headers as well.
I'm a couple of weeks into my Flutter journey. I have looked at a few tutorials on using a web service and returning data, but am unsure of a couple of things and how to apply to my web services.
I have completed my web app (written in Elevate Web Builder) and also my server side modules acting as my web services. Inside my web app I call the web service using a server request and the following parameters:
Params : Key and value pairs - used to pass authorization info
eg:
Params.Values['userid'] := 'test'
Params.Values['password'] := 'test-Password'
RequestHeaders - used to specify the content type
eg:
RequestHeaders.Values['Content-Type'] := 'text/plain'
RequestContent : Key and value pairs - used to send values to specify what to retrieve or what to save into the database
eg:
RequestContent.Values['webService'] := 'Get_StaffList'
RequestContent.Values['CompanyId'] := '123'
RequestContent.Values['OnlyActive'] := 'Y'
The Params are specified as URL parameters, but I'm not sure where I specify the RequestHeaders and RequestContent?
I have tried sending RequestHeaders and RequestContent as:
http.post('https://...', headers: {'Content-Type': 'text/plain',
'webService': 'Get_StaffList',
'CompanyId': '123',
'OnlyActive': 'Y'
});
but this didn't work. Any ideas how it should be sent in Flutter?
Thanks heaps,
Paul
Here is an example
String server = "http://localhost:8008";
userSearch(String accessToken, String searchTerm) async {
String url = server + "/_matrix/client/r0/user_directory/search";
Map<String, String> headers = {"content-type": "application/json", "authorization": "Bearer $accessToken"};
String body = jsonEncode({"search_term": searchTerm});
Response response = await post(url, headers: headers, body: body);
UserSearchObj users = UserSearchObj.fromJson(jsonDecode(response.body));
return users;
}
I just thought I'd let you know I got it working. I took what you suggested and looked at what the web service was receiving from the web app. Then modified the code in Flutter to send the data in the same format. This now works:
final response = await http.post(
Uri.encodeFull('http://mobileuser.pvapps.one:82/modules/rmo_daMLogin'),
headers: {'Content-Type': 'text/plain'},
body: 'rmoService=User_Login\n'
'UserId=fred\n'
'Password=abc123');
Thanks again for the help,
Paul