I have faced the issue like get access token in PayPal using flutter
How can I solve the issue?
try this function. hope it can work.
Future makePost() async {
String username = "*************";
String password = "*************";
var bytes = utf8.encode("$username:$password");
var credentials = base64.encode(bytes);
Map token = {
'grant_type': 'client_credentials'
};
var headers = {
"Accept": "application/json",
'Accept-Language': 'en_US',
"Authorization": "Basic $credentials"
};
var url = "https://api.sandbox.paypal.com/v1/oauth2/token";
var requestBody = token;
http.Response response = await http.post(url, body: requestBody, headers: headers);
var responseJson = json.decode(response.body);
return responseJson;
}
Related
I am making flutter app using API and I have a problem. When I want to get auth token to make request, flutter says that "Expected a value of type 'String', but got one of type '_Future'". How can I make a request with auth token without that error?
My login function, where I write the token:
loginUser() async {
final storage = new FlutterSecureStorage();
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/login");
await http
.post(uri,
headers: {"Content-Type": "application/json"},
body: jsonEncode({
"username": emailController.text,
"password": passwordController.text
}))
.then((response) async {
if (response.statusCode == 200) {
var data = json.decode(response.body);
await storage.write(key: "token", value: data["token"]);
print(data["token"]);
} else {
print(json.decode(response.body));
}
});
}
My getdata function, where i use the token:
getdata() async {
final storage = FlutterSecureStorage();
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/countries");
await http.get(uri, headers: {
"Content-Type": "application/json",
"Authorization": await storage.read(key: "token")
});
}
try this code
String token = await storage.read(key: 'token');
//make sure if there is no Bearer just token in that case just pass the token
var headers = {
'accept': 'application/json',
'Authorization': 'Bearer ${token}',
};
Uri uri = Uri.parse("http://127.0.0.1:8000/api/account/countries");
Response response = await http.get(
uri,
headers: headers
);
print (response);
I tried to make post method with Bearer Auth in dio but I got Http status error [500]
this is my code
sendData() async {
pr.show();
if (_value == null) {
Future.delayed(Duration(seconds: 0)).then((value) {
setState(() {
pr.hide();
utils.showAlertDialog(
select_area, "warning", AlertType.warning, _scaffoldKey, true);
});
});
return;
}
// Get info for attendance
var dataKey = getKey;
var dataQuery = getQuery;
var userToken = getToken;
// Add data to map
Map<String, dynamic> body = {
'key': dataKey,
'worker_id': getId,
'q': dataQuery,
'lat': _currentPosition.latitude,
'longt': _currentPosition.longitude,
'area_id': _value,
};
// Sending the data to server
final uri = utils.getRealUrl(getUrl, getPath);
Dio dio = Dio();
Map<String, String> mainheader = {
"Content-type": "application/json",
"Authorization": userToken,
};
FormData formData = FormData.fromMap(body);
final response = await dio.post(uri,
data: formData, options: Options(headers: mainheader));
var data = response.data;
and also see this image , I can see the token in my function , so what can I do to fix it
I tried this code but also same
dio.options.headers['content-Type'] = 'application/json';
dio.options.headers["authorization"] = "Bearer userToken";
Update -----
this is the details of the 500 error
as you see its same error when I make the post without auth in postman so I think the problem its from headers
and here with auth
The 500 error is a server-side error.
You should be able to find the cause of the problem on the server.
static Future<List<Storedata>> fetchStoredata() async {
const baseUrl = 'http://192.168.1.104:8000/v1/';
var storeDataResponse = await client.post(
Uri.parse('$baseUrl/me'),
headers: {"app_id": "${Storedata().appId}"},
);
if(storeDataResponse.statusCode == 200) {
return
}
}
The Storedata().appId is Model of Json Data is this format is Correct
You can call getHeader Function in all your requests and customize it,
you can check an example header function
Future<Map<String, String>> getHeader() async {
var platform = Platform.isAndroid ? PlatformTypes.ANDROID : PlatformTypes.IOS;
var locale = Intl.getCurrentLocale();
locale = locale.split("_").first;
var deviceId = DeviceInfo.getInstance()?.deviceID ?? "";
var model = DeviceInfo.getInstance()?.model ?? "";
return {
"Content-type": "application/json",
"Authorization": "Bearer " + token,
"locale": locale,
"platform": platform,
"device-id": deviceId,
};
}
var header = await getHeader();
final response = await client.post(Uri.parse(_baseUrl + url),
headers: header, body: body);
have a great day, i have a silly problem, don't mind as i am noob. ok my problem is, i have a token which i received after i login, now i have to post a data but for that i have to include this token in my header, but i don't know how to....
here is my token, which i received after login as response
{
"token": "8d18265645a87d608868a127f373558ac2e131a6"
}
Here, i have to implement in flutter
apiData.ApiData app = apiData.ApiData();
final String apiURl = app.api;
SharedPreferences pref = await SharedPreferences.getInstance();
String? email = pref.getString("useremail");
String? token = pref.getString('token');
String date = DateFormat("yyyy-MM-dd").format(DateTime.now());
String time = DateFormat("Hms").format(DateTime.now());
print(time);
print(date);
dynamic response =
await http.post(Uri.parse(apiURl + "/api/user-log/"), body: {
'user': email,
'start_time': time,
'start_date': date,
});`
Here in the documentation you can found the following snippet, where the headers are sent with the HTTP request:
Future<http.Response> createAlbum(String title) {
return http.post(
Uri.parse('https://jsonplaceholder.typicode.com/albums'),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'title': title,
}),
);
}
Add header in the post method as below:
var headers = {
'authorization': token,
"Accept": "application/json"
};
dynamic response =
await http.post(Uri.parse(apiURl + "/api/user-log/"),headers: headers), body: {
...
});
final response = await http.get(
Uri.parse(apiURl + "/api/user-log/"),
body: {}
headers: {
HttpHeaders.authorizationHeader: "<Your token here>",
},
);
Documentation here
below is the code that I tried but it didn't work, how to insert header on MultipartRequest?
var id = prefs.getInt('id');
var token = prefs.getString('accessToken');
var uri = Uri.parse('https://url.com/submit/$id');
var headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer $token'
};
var request = http.MultipartRequest('POST', uri);
request.files.add(
await http.MultipartFile.fromPath('file', _files.first.path.toString()),
);
var response = await request.send();
Headers is a map attribute of the request object, you can simply use map methods on it:
request.headers.addAll(headers)