I run script in app script to get data from gate API by GET /spot/orders and work good but, if I change status open to finished return empty.
you can see document from this URL: https://www.gate.io/docs/developers/apiv4/en/#list-orders.
this is code:
function orders() {
const key = "*****";
const secret = "*****";
const host = "https://api.gateio.ws";
const prefix = "/api/v4";
const url = "/spot/orders";
const method = "GET";
const query_param = "currency_pair=BTC_USDT&status=open";
const signature = gen_sign_(key, secret, method, prefix + url, query_param);
const headers = { "Accept": "application/json", "Content-Type": "application/json", "muteHttpExceptions": true, ...signature };
const res = UrlFetchApp.fetch(host + prefix + url + "?" + query_param , { method, headers });
console.log(res.getContentText());
}
This code is work good and give me return of my open orders.
Problem linked by this code:
const query_param = "currency_pair=BTC_USDT&status=open";
If I change status=open to status=finished.
give me return empty just []
note: I have orders buy and sell in this pair.
Related
Instagram Graph API:
https://developers.facebook.com/docs/instagram-api/
Content Publishing:
https://developers.facebook.com/docs/instagram-api/guides/content-publishing/
My code Javascript in Google App Script:
function InstagramPost() {
const id = '123456789';
const image = 'https://www.w3schools.com/images/w3schools_green.jpg';
const text = 'Hello%20World';
const access_token = 'TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST';
const container = 'https://graph.facebook.com/v11.0/' + id + '/media?image_url=' + image + '&caption=' + text + '&access_token=' + access_token;
const response = UrlFetchApp.fetch(container);
const creation = response.getContentText();
Logger.log(creation);
}
The return in my Logger of my container to Post via Instagram API request comes as follows:
{
"data": [
{
"id": "11111111111111111"
},
{
"id": "22222222222222222"
},
{
"id": "33333333333333333"
}
],
"paging": {
"cursors": {
"before": "QWOURQWNGEWRONHWENYWPETGNWQPGNPGNWEPGNWEPGNWEPNGWPENGPWEG",
"after": "WIWEPGNEPBNWE´GNÉ´BNWE´BNWÉBWNEB´WENBNWEBWEBEWBWE"
},
"next": "https://graph.facebook.com/v11.0/11111111111111111/media?access_token=PQWNFWPQINPWNBQPWNBQPWNBPQWNVQWPNVPQWVNPQWPVNQPWNVQPWVNQPWNVPQWNVQPWNVQPWVNQASASLGÇAJKSGLJAAÇSNAÇKNSVÇLKNASBÇANSBÇAS"
}
}
To make the final call for post image it is necessary to use an creation_id=:
const sendinstagram = 'https://graph.facebook.com/v11.0/' + id + '/media_publish?creation_id=' + creation + '&access_token=' + access_token;
UrlFetchApp.fetch(sendinstagram);
If the return from the container is several id in sequence, how do I know which one to define for the call?
Note: I can't loop to try every id because Instagram has a daily limit of 25 calls and posts, so if I did that I would end up with my calls just trying to post a single image.
First, we create IG Container by hitting the endpoint.
POST https://graph.facebook.com/v11.0/{ig-user-id}/media?image_url={image-url}&caption={caption}&access_token={access-token}
Once you have the IG container ID then we again make a POST request to post the Image.
POST https://graph.facebook.com/v11.0/{ig-user-id}/media_publish?creation_id={creation-id}&access_token={access-token}
I think you have to include the version in container and sendinstagram which is v11.0 (latest as if now).
I found the correct way to publish images:
var formData = {
'image_url': image,
'caption': text,
'access_token': access_token
};
var options = {
'method' : 'post',
'payload' : formData
};
const container = 'https://graph.facebook.com/v11.0/' + instagram_business_account + '/media';
const response = UrlFetchApp.fetch(container, options);
const creation = response.getContentText();
var data = JSON.parse(creation);
var creationId = data.id
var formDataPublish = {
'creation_id': creationId,
'access_token': access_token
};
var optionsPublish = {
'method' : 'post',
'payload' : formDataPublish
};
const sendinstagram = 'https://graph.facebook.com/v11.0/' + instagram_business_account + '/media_publish';
UrlFetchApp.fetch(sendinstagram, optionsPublish);
I'm trying to collect tweets from Twitter API V2:
https://developer.twitter.com/en/docs/twitter-api/tweets/timelines/api-reference/get-users-id-tweets
The script I'm using to send the tweet value data to a Google Sheets cell is:
function TwitterTest() {
var string_Screen_name = "1310800524619386880";
var string_Consumer_key = "AAAAAAAAAAAAAAAAAAAAAAAAAA";
var string_Consumer_secret = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
var tokenUrl = "https://api.twitter.com/oauth2/token";
var tokenCredential = Utilities.base64EncodeWebSafe(string_Consumer_key + ":" + string_Consumer_secret);
var tokenOptions = {
headers : {
Authorization: "Basic " + tokenCredential,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
method: "post",
payload: "grant_type=client_credentials"
};
var responseToken = UrlFetchApp.fetch(tokenUrl, tokenOptions);
var parsedToken = JSON.parse(responseToken);
var token = parsedToken.access_token;
var apiUrl = "";
var responseApi = "";
var apiOptions = {
headers : {
Authorization: 'Bearer ' + token
},
"method" : "get"
};
var apiUrl = 'https://api.twitter.com/2/users/'+ string_Screen_name +'/tweets?expansions=attachments.poll_ids,attachments.media_keys,author_id,entities.mentions.username,geo.place_id,in_reply_to_user_id,referenced_tweets.id,referenced_tweets.id.author_id&tweet.fields=attachments,author_id,context_annotations,conversation_id,created_at,entities,geo,id,in_reply_to_user_id,lang,possibly_sensitive,public_metrics,referenced_tweets,reply_settings,source,text,withheld&user.fields=created_at,description,entities,id,location,name,pinned_tweet_id,profile_image_url,protected,public_metrics,url,username,verified,withheld&place.fields=contained_within,country,country_code,full_name,geo,id,name,place_type&poll.fields=duration_minutes,end_datetime,id,options,voting_status&media.fields=duration_ms,height,media_key,preview_image_url,type,url,width,public_metrics,non_public_metrics,organic_metrics,promoted_metrics';
responseApi = UrlFetchApp.fetch(apiUrl, apiOptions);
var obj_data = JSON.parse(responseApi.getContentText());
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Tweets").getRange("A3").setValue(obj_data.data);
}
The result obtained:
{attachments={media_keys=[Ljava.lang.Object;#1152e2a4}, entities={urls=[Ljava.lang.Object;#1373921e}, possibly_sensitive=false, conversation_id=1402411015724175370, public_metrics={like_count=1, reply_count=0, quote_count=0, retweet_count=0}, created_at=2021-06-08T23:43:36.000Z, source=Twitter Web App, id=1402411015724175370, text=ALERT: New high roller bet posted!
A parlay bet has been placed for $5,403.62 to win $6,241.18.
To view this bet or copy it https:// t.co /lrBXjHN0At https:// t.co /nBPMsgXI2g, author_id=1310800524619386880, lang=en, reply_settings=everyone}
Specifically in urls the result is:
urls=[Ljava.lang.Object;#1373921e}
The expected result in urls would look something like (example collected from Twitter API V2 website):
In your situation, is the following modification the result you expect?
From:
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Tweets").getRange("A3").setValue(obj_data.data);
To:
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Tweets").getRange("A3").setValue(JSON.stringify(obj_data.data));
I am trying to send a POST request to the /Finances endpoint and cannot get past the error that says:
<ErrorResponse xmlns="http://mws.amazonservices.com/schema/Finances/2015-05-01">
<Error>
<Type>Sender</Type>
<Code>SignatureDoesNotMatch</Code>
<Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message>
</Error>
</ErrorResponse>
I have taken the parameters right off of successful queries on Scratchpad and run them through my hashing process and am calculating signatures that match those calculated on Scratchpad so I know my signature process is accurate but even in those instances, I am still receiving the mismatched Signature error. This tells me that maybe there is something else wrong with my request, however I've tried many different variations and mimicked the documentation with no success.
I've tried ordering my parameters in ASCII alphabetical as well as in the order that scratchpad shows (which is not alphabetical) and neither works. There are no typos in any of my keys or extra spaces. I am lost on what could be causing this and would really appreciate some help if you've worked with mws. Below is my code:
const method = "POST";
const hostName = "mws.amazonservices.com";
const requestUri = "/Finances/2015-05-01";
const keyId = XXXXXXXXXXXX;
const action = "ListFinancialEvents";
const authToken = XXXXXXXXXx;
const sellerId = XXXXXXXXX;
const secretKey = XXXXXXXXXXXx;
const signatureVersion = "2";
const timestamp = new Date();
const formattedTimestamp = timestamp.toISOString();
const version = "2015-05-01";
const signatureMethod = "HmacSHA256";
const postedAfter = "2020-06-07T0:00:00Z";
const queryString =
"AWSAccessKeyId=" +
encodeURIComponent(keyId) +
"&Action=" +
encodeURIComponent(action) +
"&MWSAuthToken=" +
encodeURIComponent(authToken) +
"&PostedAfter=" +
encodeURIComponent(postedAfter) +
"&SellerId=" +
encodeURIComponent(sellerId) +
"&SignatureMethod=" +
encodeURIComponent(signatureMethod) +
"&SignatureVersion=" +
encodeURIComponent(signatureVersion) +
"&Timestamp=" +
encodeURIComponent(formattedTimestamp) +
"&Version=" +
encodeURIComponent(version);
const stringToSign =
method + "\n" + hostName + "\n" + requestUri + "\n" + queryString;
const signature = crypto
.createHmac("sha256", secretKey)
.update(stringToSign)
.digest("base64");
const queryBody = querystring.stringify({
AWSAccessKeyId: keyId,
Action: action,
MWSAuthToken: authToken,
PostedAfter: postedAfter,
SellerId: sellerId,
SignatureMethod: signatureMethod,
SignatureVersion: signatureVersion,
Timestamp: formattedTimestamp,
Version: version,
Signature: signature,
});
const options = {
hostname: hostName,
path: requestUri,
method: method,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": queryBody.length,
Host: "mws.amazonservices.com",
"User-Agent": "myMWSApp/1.0 (Language=Javascript)",
},
};
const req = https.request(options, (res) => {
console.log("statusCode", res.statusCode);
console.log("headers:", res.headers);
res.on("data", (d) => {
process.stdout.write(d);
});
});
req.on("error", (e) => {
console.error("ERROR:", e);
});
req.write(queryBody);
req.end();
I'm adding a contact me section to a website. I want to be able to send the data from the forms with JS, and then receive and do something with the data with Node. I understand that there are frameworks and libraries that can handle this stuff, but I would like to build it from scratch so that I have a better understanding of what is happening.
I currently have a section of JS (see below) that is taking the form data, and sending it as a POST request to the node script, but I can't seem to wrap my head around what is happening with node, or how to receive the data with the node script. Any help in pointing me in the right direction is greatly appreciated.
const name = $(".name");
const email = $(".email");
const message = $(".message");
const submitButton = $(".submitButton");
const nameRegex = /([a-zA-Z\s-])/g;
const emailRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g;
const messageRegex = /([a-zA-Z\s.,?!$%&])/gm;
const url = "../node/contactMeSubmissionHandler.js"
submitButton.click(function(){
let nameContents = name.val().match(nameRegex).join("");
let emailContents = email.val().match(emailRegex).join("");
let messageContents = message.val().match(messageRegex).join("");
// if (emailRegex.test(emailContents) == true) {
// let emailValid = emailContents;
// } else {
// console.log("Email is invalid");
// };
const data = {
email: emailContents,
name: nameContents,
message: messageContents
}
$.post(url, data, function(data, status){
console.log(`${data} and status is ${status}`);
})
})
I like to write from scratch too. Here is working code which is called from a command line to get a token.
// clientEx.js
var http = require('http');
var fs = require('fs');
const _SERVER = "dcsmail.net"; /* dcsmail.net */
// Callback function is used to deal with response
//
var callback = function (response)
{
// update stream with data
var body = '';
response.on('data', function(data) {
body += data;
});
response.on ('end', function()
{
// Data received completely.
fs.writeFileSync ("temp.lst", body, 'utf8');
// console.log ("clientEx.js received: " + body);
});
}
if ((process.argv[2] == null) || (process.argv[3] == null) || (process.argv[4] == null) || (process.argv[5] == null))
{
console.log ("clientEx.js usage:<user email> <user password> <destination> <GUID>");
}
else
{
var Ef_email = encodeURI (process.argv[2]);
var Ef_pass = encodeURI (process.argv[3]);
var Ef_dest = encodeURI (process.argv[4]);
var Ef_guid = encodeURI (process.argv[5]);
var post_data = ("f_email=" + Ef_email +
"\&" + "f_pass=" + Ef_pass +
"\&" + "f_dest=" + Ef_dest +
"\&" + "f_guid=" + Ef_guid);
// Options to be used by request
var options = {
host: _SERVER,
port: '80',
path: '/DCSM/tokenP10.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength (post_data)
}
};
// console.log ("clientEx.js using " + _SERVER + ":" + options.port + options.path);
// request the token from the host
try
{
var req = http.request (options, callback);
req.write (post_data);
req.end();
}
catch (error)
{
fs.writeFileSync ("temp.lst", "Host access failed\n", 'utf8');
}
}
You should be able to adapt that to your needs.
Use this code to create a server and check the log in console for different request attributes.
const http = require('http');
http
.createServer((request, response) => {
console.log(request);
response.end();
})
.listen(3000);
Make GET and POST request to http://localhost:3000/ and look for method, headers etc.
See more here and here.
{"errors":[{"code":32,"message":"Could not authenticate you."}]}
This is what I get when trying to perform a GET users/show request to Twitter. Some background:
User is authenthicated in my Android app through ParseTwitterUtils;
From Android, I call a parse.com Cloud Code function passing in the user token and token secret (looks like bad practice, but for now I'd just like to see this work);
From Cloud Code, I format the auth header using this github library. This is needed as explained here.
You can see some of my code below. Android launch code:
HashMap<String, Object> params = new HashMap<>();
params.put("twitterId", ParseTwitterUtils.getTwitter().getUserId());
params.put("authToken", ParseTwitterUtils.getTwitter().getAuthToken());
params.put("authTokenSecret", ParseTwitterUtils.getTwitter().getAuthTokenSecret());
ParseCloud.callFunctionInBackground("fetchPictureFromTwitter", params, ... );
Cloud code main function:
Parse.Cloud.define("fetchPictureFromTwitter", function(request, response) {
var twitterId = request.params.twitterId;
var authToken = request.params.authToken;
var authTokenSecret = request.params.authTokenSecret;
var url = "https://api.twitter.com/1.1/users/show.json";
Parse.Cloud.httpRequest({
url: url,
followRedirects: true,
headers: {
"Authorization": getOAuthSignature(url,authToken,authTokenSecret)
},
params: {
user_id: twitterId
}
}).then(...)
And lastly here's getOAuthSignature, the function used to sign the request (I took this from the example page in the github link):
var getOAuthSignature = function(url, authToken, authTokenSecret) {
var nonce = OAuth.nonce(32);
var ts = Math.floor(new Date().getTime() / 1000);
var timestamp = ts.toString();
var consumerKey = <MY-APP-CONSUMER-KEY>
var consumerSecret = <MY-APP-CONSUMER-SECRET>
var accessor = {
"consumerSecret": consumerSecret,
"tokenSecret": authTokenSecret
};
var params = {
"oauth_version": "1.0",
"oauth_consumer_key": consumerKey,
"oauth_token": authToken,
"oauth_timestamp": timestamp,
"oauth_nonce": nonce,
"oauth_signature_method": "HMAC-SHA1"
};
var message = {
"method": "GET",
"action": url,
"parameters": params
};
OAuth.SignatureMethod.sign(message, accessor);
var normPar = OAuth.SignatureMethod.normalizeParameters(message.parameters);
var baseString = OAuth.SignatureMethod.getBaseString(message);
var sig = OAuth.getParameter(message.parameters, "oauth_signature") + "=";
var encodedSig = OAuth.percentEncode(sig);
return 'OAuth oauth_consumer_key="'+consumerKey+'", oauth_nonce=' + nonce + ', oauth_signature=' + encodedSig + ', oauth_signature_method="HMAC-SHA1", oauth_timestamp=' + timestamp + ',oauth_token="'+authToken+'", oauth_version="1.0"'
};
What could be wrong? I've spent two days on the matter now and I don't know what to do anymore.
The issue here was that user_id="<user-id> has to be encoded in the request header as well as all the other oauth_* parameters. So I had to change this section:
var params = {
"user_id": twitterId, // <- add here
"oauth_version": "1.0",
"oauth_consumer_key": consumerKey,
"oauth_token": authToken,
"oauth_timestamp": timestamp,
"oauth_nonce": nonce,
"oauth_signature_method": "HMAC-SHA1"
};
And I'm passing the userId from the outer function, like getOAuthSignature(url,twitterId,authToken,authTokenSecret).
As for passing auth token data from device to cloud, this is probably not needed because you can find all the authentication info in the authData field of any ParseUser (as long as it is linked with twitter or Facebook).