How make local http request in flutter? - django

I'm making an app, and i already have a server running in my local. I can acess trought my navigator the url:
Request URL: http://localhost:4444/categorie?page_size=15&page=1
Request Method: GET
Status Code: 200 OK
Remote Address: 127.0.0.1:4444
Referrer Policy: no-referrer-when-downgrade
Preview:
{
"count": 4,
"next": null,
"previous": null,
"results": [
{
"uid": "_b656062d3754",
"name": "Pinga"
},
{
"uid": "_0c644473c244",
"name": "Cerveja"
},
{
"uid": "_75df557ccbaa",
"name": "Vinhos"
},
{
"uid": "_8e32ce3baded",
"name": "Refrigerantes"
}
]
}
But when i try in flutter, the request never respond:
getCategories() async {
String url = 'http://localhost:4444/categorie?page_size=15&page=1';
var response = await http.get(url);
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON
return response.body;
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}
}
I'm running the server in my Windows10 using Django. And my flutter app is in the Android Studio using a Virtual Machine as device.
I tryed to change the ip to 127.0.0.1 and 10.0.0.1 but still not working. Have i change the host of Django or enable any configuration in my flutter or inside VirutalBox?
Request to other sites is working well. The problem is in local.
My dependencies:
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^0.1.2
http: any
dev_dependencies:
flutter_test:
sdk: flutter

Your localhost on your PC is not the same on your Android emulator. To access your PC's localhost from the Android emulator, you need to point to 10.0.2.2.
This means that you need to change your code to:
String url = 'http://10.0.2.2:4444/categorie?page_size=15&page=1';

Use this in pubspec file under dependencies:
http: ^0.12.0+2
Use this method for Http request
getCategories() async {
final response = await http.get("http://localhost:4444/categorie?page_size=15&page=1",
headers: {
'content-type': 'application/json',
},
);
if (response.statusCode == 200) {
final result = json.decode(response.body);
var list = result['results'] as List;
// make a model class
List<Categories> categories_= list.map((i) => Categories.fromJson(i)).toList();
setState(() => {
// update value
});
} else {
setState(() => {
// Show error
});
}
}
Model class:
class Categories{
String uid;
String name;
Categories({this.uid, this.name});
Categories.fromJson(Map<String, dynamic> json) {
uid = json['uid'];
name = json['name'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['uid'] = this.uid;
data['name'] = this.name;
return data;
}
}

Related

How to set up Paypal Smart Buttons with Flask?

I already did a server-side setup for Paypal Payments. I get the product price from the Html form and then creates a payment with paypalrestsdk module. Important Chunk of code from the whole system is here:-
payment = paypalrestsdk.Payment({
"intent": "sale",
# Set payment method
"payer": {
"payment_method": "paypal"
},
# Set redirect URLs
"redirect_urls": {
"return_url": url_for('after_payment_done_2_sol', hash_id=hash_id, user_id=current_user.user_id, _external=True),
"cancel_url": url_for('topup', _external=True)
},
# Set transaction object
"transactions": [{
"amount": {
"total": query.total_price,
"currency": "USD"
},
"description": f"Payment Method for paying {query.total_price} for Top Up"
}]
})
if payment.create():
print('Payment "{}" created successfully'.format(payment.id))
for link in payment.links:
if link.method == "REDIRECT":
redirect_url = str(link.href)
print('Redirect for approval: {}'.format(redirect_url))
return redirect(redirect_url)
So this will create a link to "Pay X Amount via Paypal". But i want to integrate smart Buttons like here
https://developer.paypal.com/demo/checkout/#/pattern/server. Now here there is a codeblocks like:
<script>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
// How Does this work?????????????????????
// Set up the transaction
createOrder: function(data, actions) {
return fetch('/demo/checkout/api/paypal/order/create/', {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(data) {
return data.orderID;
});
},
// ???????????????????????????????????????? How does this Work?????
// Finalize the transaction
onApprove: function(data, actions) {
return fetch('/demo/checkout/api/paypal/order/' + data.orderID + '/capture/', {
method: 'post'
}).then(function(res) {
return res.json();
}).then(function(details) {
// Show a success message to the buyer
alert('Transaction completed by ' + details.payer.name.given_name + '!');
});
}
}).render('#paypal-button-container');
</script>
So here how does onAprrove and createOrder Works? And how should i set up my route in flask? Any help Please!
That is a server-side integration, so /demo/.... needs to be replaced with URLs that will trigger server-side code, on your webserver.
If you want javascript for a client-side integration, use https://developer.paypal.com/demo/checkout/#/pattern/client

loopback rest connection headers authorization

I'm trying to access the Shopify Orders API in a Loopback application. I have the following data source:
"ShopifyRestDataSource": {
"name": "ShopifyRestDataSource",
"connector": "rest",
"operations": [{
"template": {
"method": "GET",
"url": "https://mystore.myshopify.com/admin",
"headers": {
"accepts": "application/json",
"content-type": "application/json"
}
},
"headers": {
"Authorization": "Basic MzdiOD..."
},
"functions": {
"find": []
}
}]
}
And then I attempt a simple call:
var ds = app.dataSources.ShopifyRestDataSource;
ds.find(function(err, response, context) {
if (err) throw err;
if (response.error) {
next('> response error: ' + response.error.stack);
}
console.log(response);
next();
});
I'm getting the following exception message:
Error: {"errors":"[API] Invalid API key or access token (unrecognized login or wrong password)"}
at callback (/order-api/node_modules/loopback-connector-rest/lib/rest-builder.js:529:21)
The Shopify API authenticates by basic HTTP authentication and I'm sure my request works since the same data works with curl. What am I doing wrong?
I couldn't find the "Loopback way" to do this and I couldn't wait, so I just wrote a simple https Node call. I'll paste this in here but I won't accept it as the answer. I'm still hoping someone will provide the right answer.
let response;
const options = {
hostname: 'mystore.myshopify.com',
port: 443,
path: '/admin/orders.json',
method: 'GET',
auth: `${instance.api_key}:${instance.password}`
};
const req = https.request(options, (res) => {
res.setEncoding('utf8');
let body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
let jsonResponse = JSON.parse(body);
// application logic goes here
response = 'ok';
});
});
req.on('error', (e) => {
response = e.message;
});
req.end();

How dis you get oauth-1.0a and crypto to work with WP-API

I am using crypto and oauth-1.0a from nmp in ionic2 application. I want to access WP-API which is correctly set to handle authentication, I tested this using Postman.
Http.Get results in the following error:
{
"_body": {
"isTrusted": true
},
"status": 0,
"ok": false,
"statusText": "",
"headers": {},
"type": 3,
"url": null
}
The options generated that I pass as argument to Http.Get are as follows:
{“method”:0,“headers”:{“Authorization”:“OAuth oauth_consumer_key=”",
oauth_nonce=“jSZGPwkj4quRGMb0bhBLYKwmc3BGfrQw”, oauth_signature=“x3zseS3XTFBLMsNDLXC4byn2UDI%3D”,
oauth_signature_method=“HMAC-SHA1”, oauth_timestamp=“1522414816”,
oauth_token="",
oauth_version=“1.0"”},“body”:null,“url”:"",“params”:{“rawParams”:"",“queryEncoder”:{},“paramsMap”:{}},“withCredentials”:null,“responseType”:null}
Part of code:
this.oauth = new OAuth({
consumer: {
key: this.apiconstant.consumerkey,
secret: this.apiconstant.consumersecret
},
signature_method: ‘HMAC-SHA1’,
hash_function: hash_function_sha1,
realm:’’
});
let request_data = {
url: ‘’,
method: ‘GET’
};
let token={
key: this.apiconstant.token,
secret: this.apiconstant.tokensecret
}
//This part doesn’t seem to work
this.authkey = this.oauth.authorize(request_data,token);
this.keyoauth = new URLSearchParams();
for (let param in this.authkey) {
this.keyoauth.set(param, this.authkey[param]);
}
let options = new RequestOptions({
method: ‘GET’,//request_data.method
url: ‘’,
headers: this.oauth.toHeader(this.oauth.authorize(request_data,token)),
search: this.keyoauth
});
this.http.get(’’,options)
.map(res => res.json()).subscribe(data=>{
console.log(‘Resulting data’ + JSON.stringify(data));
},
error=>{
console.log(‘Got error’+JSON.stringify(error));
});
//Error part executed
What am I missing here? I’m testing my app on android device. Without authentication I get desired results from the WP-API (Wordpress), that is if the Oauth is disabled on WP-API.
Please help! This is my second day on this. I should also let you know I’m new on these technologies but I’m able to research and understand how they work.

before Remote in Loopback

I'm trying to use the before Remote hook in loopback to check an user token before the call of my remote method, but the thing is that I can only return a javascript Error, like these.
"error": {
"statusCode": 401,
"name": "Error",
"message": ""
}
This is the code that i'm using in the before remote.
Model.beforeRemote('method', function (context, unused, next) {
let token = Model.app.models.Token;
let id = context.args.Id;
let date = moment();
Rx.Observable.fromPromise(token.find({
where: {
and: [
{ id: id, },
{ expiration: { gt: date } }
]
}
})).subscribe((token => {
if (token.length > 0) {
next();
} else {
let err = new Error();
err.status = 401;
delete err.stack;
return next()
}
}))
});
And I need a "custom" response that isn't an error, something like these.
{
"success": false,
"data": {
"service": "self",
"operation": "rest",
"code": "unauthorized"
},
"message": "Invalid token"
}
I tried with the after Remote hook and I can change the response to get something like that, but I want to get a quicker response in the case that the token is invalid.
Is there any way to achieve this with the before hook? or I had to use after hook?
Thanks
You may want to pass the error to the next function:
return next(err)

Skype Web SDK stops updating presence

I am using Skype Web SDK with ionic.
I have two buttons in app after login like "Idle" and "Busy". When I click on it, its changing status of user on Skype for business o365 accordingly.
Now, When I run the app, After login, its work well for first one hour or so and then the app stops reflecting status on Skype For Business.
I get 404 - not found error once it stops updating status.
POST https://webpooldb41e02.infra.lync.com/ucwa/oauth/v1/applications/1145363530/me/reportMyActivity 404 (Not Found)
below is the code I am using for authentication,
let authContext = new Microsoft.ADAL.AuthenticationContext("https://login.windows.net/common");
authContext.acquireTokenSilentAsync("https://graph.windows.net", "Client_id")
.then(function(res) {
console.log(res);
cordova.plugins.backgroundMode.disableWebViewOptimizations();
Skype.initialize({
apiKey: 'Api Key'
}, function (api) {
console.log(new Date().toLocaleString()+" 2");
console.log(api.UIApplicationInstance);
//console.log(this.ucwaData);
window.skypeWebApp = "";
window.skypeWebApp = api.UIApplicationInstance;
window.skypeWebApp.signInManager.signIn({
"client_id": client_id,
"origins": ["https://webdir.online.lync.com/autodiscover/autodiscoverservice.svc/root"],
"cors": true,
"version": 'SkypeOnlinePreviewApp/1.0.0',
"redirect_uri": 'https://login.microsoftonline.com/common/oauth2/nativeclient'
}).then(function () {
console.log(new Date().toLocaleString()+" done");
});
}, function (err) {
console.log(new Date().toLocaleString()+" 3");
console.log(err);
});
}, function () {
cordova.plugins.backgroundMode.disableWebViewOptimizations();
// We require user credentials so triggers authentication dialog
authContext.acquireTokenAsync("https://graph.windows.net", "client_id", "https://login.microsoftonline.com/common/oauth2/nativeclient")
.then(function(res){
if (typeof(document.getElementById("login_with_office")) != 'undefined' && document.getElementById("login_with_office") != null)
{
document.getElementById("login_with_office").innerHTML = "Please wait … Connecting";
}
console.log(res);
//document.getElementById("login_with_office").setAttribute('disabled', 'disabled');
ctrl.loginwitho365();
}, function (err) {
console.log(new Date().toLocaleString()+" Failed to authenticate: " + err);
});
});
And Below is the code I am using for updating status,
window.skypeWebApp.signInManager.state.get().then(function (stat) {
if(stat == "SignedIn")
{
window.skypeWebApp.personsAndGroupsManager.mePerson.status.set(availability);
}
else
{
//Signin COde
}
});