Get json respons from http get respons? - autocode

Please tell me how to get json response?
I get base4 by example:
// Using Node.js 14.x +
// use "lib" package from npm
const lib = require('lib')({token: null /* link an account to create an auth token */});
// make API request
let result = await lib.http.request['#1.1.6'].get({
url: null // required
});
https://autocode.com/lib/http/request/#get

Using axios package will be easier. It's default response type is json.
const axios = require('axios');
let result = await axios.get('your_url')
});

Related

Next.js rewrites + custom dynamical header for axios on the server-side

How i can do dynamical header for axios on the serve-side? I want to make functionality of cities, without edit nextjs folder structure. Rewrities from nextjs solves my problem, but I can't set the header for axios request functions on the server side. useRouter() hook returns non-proxied path.
// next.config.js
...
async Rewrites() {
return [
{
source: '/new-york/:path*',
destination: '/:path*',
},
]
}
...
Im tried use axios intreception function:
// destination _app.js
export default function AxiosInterceptors() {
...
const router = useRouter();
const asPath = router.asPath; // asPath return not non-proxied path, if i use url /new-york/blogs, here i see /blogs;
apiQr.interceptors.request.use(function (config) {
config.headers['city'] = asPath.includes('/new-york') ? '2' : '1'; // city id
return config;
}, function (error) {
return Promise.reject(error);
});
...
}
Im also tried set headers from NextJS _middleware.js but there is no access to axios requests and the axios interceptor function is not called there.
Where and how can I get a stable variable depending on the entered url on the server side so that I can adjust the axios headers?
I expect to get the proxied url in the axios interceptors instance as I showed above, but I get the proxied path.

Can I can return json list from HttpClientResponse

I am trying to connect with our server using dart and flutter. I get an error in certificate server, I get the code and I get response exactly, but the problem is the response keeps coming back as a string. I want it as a list to loop through it.
HttpClient client = new HttpClient();
client.badCertificateCallback =((X509Certificate cert, String host, int port) => true);
String url ='https://xxx';
//Map map = { "email" : "email" , "password" : "password"};
HttpClientRequest request = await client.getUrl(Uri.parse(url));
//request.headers.set('content-type', 'application/json');
//request.add(utf8.encode(json.encode(map)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
I have simple code to get a JSON response as a list. The problem is our server is using https and nginx to take all request to the correct port. Previous code worked but I need to respond with a list.
simple code is :
String apiURL = "https://jsonplaceholder.typicode.com/posts";
http.Response response = await http.get(apiURL);
return json.decode(response.body);
You won't get a list. You would get flat json which you would need to process. Processing can be done using simple script using powershell.

How to dispatch a Paypal IPN to a Google Cloud function?

I've read here that it's possible to send an IPN directly to a Google cloud function. I have my Google Cloud functions running on Firebase on an index.js file.
I've set up my Paypal buttons to send the IPN to a page on my webapp.
Here is an example of one of the functions I'm running off Google Cloud Functions/Firebase:
// UPDATE ROOMS INS/OUTS
exports.updateRoomIns = functions.database.ref('/doors/{MACaddress}').onWrite((change, context) => {
const beforeData = change.before.val();
const afterData = change.after.val();
const roomPushKey = afterData.inRoom;
const insbefore = beforeData.ins;
const insafter = afterData.ins;
if ((insbefore === null || insbefore === undefined) && (insafter === null || insafter === undefined) || insbefore === insafter) {
return 0;
} else {
const updates = {};
Object.keys(insafter).forEach(key => {
updates['/rooms/' + roomPushKey + '/ins/' + key] = true;
});
return admin.database().ref().update(updates); // do the update}
}
return 0;
});
Now question:
1) I want to add another function to process IPN from Paypal as soon as I have a transaction. How would I go about this?
I'll mark the answer as correct if solves this first question.
2) how would that Google cloud function even look like?
I'll create another question if you can solve this one.
Note I am using Firebase (no other databases nor PHP).
IPN is simply a server that tries to reach a given endpoint.
First, you have to make sure that your firebase plan supports 3rd party requests (it's unavailable in the free plan).
After that, you need to make an http endpoint, like so:
exports.ipn = functions.http.onRequest((req, res) => {
// req and res are instances of req and res of Express.js
// You can validate the request and update your database accordingly.
});
It will be available in https://www.YOUR-FIREBASE-DOMAIN.com/ipn
Based on #Eliya Cohen answer:
on your firebase functions create a function such as:
exports.ipn = functions.https.onRequest((req, res) => {
var reqBody = req.body;
console.log(reqBody);
// do something else with the req.body i.e: updating a firebase node with some of that info
res.sendStatus(200);
});
When you deploy your functions go to your firebase console project and check your functions. You should have something like this:
Copy that url, go to paypal, edit the button that's triggering the purchase, scroll down to Step 3 and at the bottom type:
notify_url= paste that url here
Save changes.
You can now test your button and check the req.body on your firebase cloud functions Log tab.
Thanks to the answers here, and especially to this gist: https://gist.github.com/dsternlicht/fdef0c57f2f2561f2c6c477f81fa348e,
.. finally worked out a solution to verify the IPN request in a cloud func:
let CONFIRM_URL_SANDBOX = 'https://ipnpb.sandbox.paypal.com/cgi-bin/webscr';
exports.ipn = functions.https.onRequest((req, res) => {
let body = req.body;
logr.debug('body: ' + StringUtil.toStr(body));
let postreq = 'cmd=_notify-validate';
// Iterate the original request payload object
// and prepend its keys and values to the post string
Object.keys(body).map((key) => {
postreq = `${postreq}&${key}=${body[key]}`;
return key;
});
let request = require('request');
let options = {
method: 'POST',
uri : CONFIRM_URL_SANDBOX,
headers: {
'Content-Length': postreq.length,
},
encoding: 'utf-8',
body: postreq
};
res.sendStatus(200);
return new Promise((resolve, reject) => {
// Make a post request to PayPal
return request(options, (error, response, resBody) => {
if (error || response.statusCode !== 200) {
reject(new Error(error));
return;
}
let bodyResult = resBody.substring(0, 8);
logr.debug('bodyResult: ' + bodyResult);
// Validate the response from PayPal and resolve / reject the promise.
if (resBody.substring(0, 8) === 'VERIFIED') {
return resolve(true);
} else if (resBody.substring(0, 7) === 'INVALID') {
return reject(new Error('IPN Message is invalid.'));
} else {
return reject(new Error('Unexpected response body.'));
}
});
});
});
Also thanks to:
https://developer.paypal.com/docs/classic/ipn/ht-ipn/#do-it
IPN listener request-response flow: https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNImplementation/
To receive IPN message data from PayPal, your listener must follow this request-response flow:
Your listener listens for the HTTPS POST IPN messages that PayPal sends with each event.
After receiving the IPN message from PayPal, your listener returns an empty HTTP 200 response to PayPal. Otherwise, PayPal resends the IPN message.
Your listener sends the complete message back to PayPal using HTTPS POST.
Prefix the returned message with the cmd=_notify-validate variable, but do not change the message fields, the order of the fields, or the character encoding from the original message.
Extremely late to the party but for anyone still looking for this, PayPal have made a sample in their JS folder on their IPN samples Github repo.
You can find this at:
https://github.com/paypal/ipn-code-samples/blob/master/javascript/googlecloudfunctions.js

How can I upload a PDF using Dart's HttpClient?

I need to post a PDF file to a remote REST API, and I can't for the life of me figure it out. No matter what I do, the server responds that I have not yet associated an object with the file parameter. Let's say that I have a PDF called test.pdf. This is what I've been doing so far:
// Using an HttpClientRequest named req
req.headers.contentType = new ContentType('application', 'x-www-form-urlencoded');
StringBuffer sb = new StringBuffer();
String fileData = new File('Test.pdf').readAsStringSync();
sb.write('file=$fileData');
req.write(sb.toString());
return req.close();
Thus far, I've tried virtually every combination and encoding of the data that I write() to the request, but to no avail. I've tried sending it as codeUnits, I've tried encoding it using a UTF8.encode, I've tried encoding it using a Latin1Codec, everything. I'm stumped.
Any help would be greatly appreciated.
You can use MultipartRequest from the http package :
var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'john#doe.com';
request.files.add(new http.MultipartFile.fromFile(
'package',
new File('build/package.tar.gz'),
contentType: new ContentType('application', 'x-tar'));
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});
Try using the multipart/form-data header rather than x-www-form-urlencoded. This should be used for binary data, also can you show your full req request?
void uploadFile(File file) async {
// string to uri
var uri = Uri.parse("enter here upload URL");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request
request.fields["user_id"] = "text";
// multipart that takes file.. here this "idDocumentOne_1" is a key of the API request
MultipartFile multipartFile = await http.MultipartFile.fromPath(
'idDocumentOne_1',
file.path
);
// add file to multipart
request.files.add(multipartFile);
// send request to upload file
await request.send().then((response) async {
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}).catchError((e) {
print(e);
});
}
I used file picker to pick file.
Here is the codes for pick file.
Future getPdfAndUpload(int position) async {
File file = await FilePicker.getFile(
type: FileType.custom,
allowedExtensions: ['pdf','docx'],
);
if(file != null) {
setState(() {
file1 = file; //file1 is a global variable which i created
});
}
}
here file_picker flutter library.

simple Google Drive access with Dart

I am trying to read a basic text file(no authorization needed) from google drive with Dart. The code below returns a 400 Error. If the API_KEY is removed then a 403 error. I can input the file id into the Google get file reference page and it will return the metadata correctly.
Any Ideas would be great. Thanks
final url = "https://www.googleapis.com/drive/v2/files/FILE?key={API_KEY}";
var request = new HttpRequest();
request.on.loadEnd.add( (Event e)
{
if (request.status == 200)
{
var data = JSON.parse(request.responseText);
query("#file").text = data;
}
else
{
query("#file").text = "Error ${request.status}: ${request.statusText}";
}
});
request.open("GET", url);
request.send();
Your best bet is to use the drive_v2_api_client.
This can be done by setting up your google console apis with the following settings for localhost testing with DartEditor
Redirect URIs: http://127.0.0.1:3030/oauth2callback
JavaScript origins: http://127.0.0.1:3030
Then use the dart drive package drive_v2_api_client by putting the following depenencies in your pubspec.yaml file.
dependencies:
drive_v2_api_client:
git: git://github.com/Scarygami/dart_drive_v2_api_client.git
This example allows the client to get the fileid after the client has authenticated with the client id.
import 'dart:html';
import 'dart:json';
import "package:drive_v2_api_client/drive_v2_api_client.dart" as drivelib;
import "package:google_oauth2_client/google_oauth2_client.dart";
final CLIENT_ID = "<YOUR CLIENT ID FROM CONSOLE API>";
final SCOPES = [drivelib.Drive.DRIVE_FILE_SCOPE];
void main() {
var fileid = "1B_cGCNFjnK3dDriTMLsSS_zExfGFkQeewb3dcP4xSPg";
var auth = new OAuth2(CLIENT_ID, SCOPES);
var drive = new drivelib.Drive(auth);
drive.makeAuthRequests = true;
var loginButton = query("#login");
var output = query("#text");
loginButton.on.click.add((Event e) {
auth.login().then((token) {
output.appendHtml("Got Token ${token.type} ${token.data}<br><br>");
drive.files.get(fileid)
..then((data) {
output.appendHtml(data.toString());
});
});
});
}
You can find all the source code to a working example here https://gist.github.com/4588427

Resources