How to create a valid signature message to POST an order to the Kucoin Future API? - json

I am trying to place an order but it gives me this error:
{"code":"400005","msg":"Invalid KC-API-SIGN"}
I'll be so thankful if someone check my code and let me know the problem
import requests
import time
import base64
import hashlib
import hmac
import json
import uuid
api_key = 'XXXXXXXXXXXXXXXXXXXXXXX'
api_secret = 'XXXXXXXXXXXXXXXXXXXXXX'
api_passphrase = 'XXXXXXXXXXXXXXX'
future_base_url = "https://api-futures.kucoin.com"
clientOid = uuid.uuid4().hex
params = {
"clientOid": str(clientOid),
"side": str(side),
"symbol": str(symbol),
"type": "limit",
"leverage": "5",
"stop": "down",
"stopPriceType": "TP",
"price": str(price),
"size": int(size),
"stopPrice": str(stopprice)
}
json_params = json.dumps(params)
print(json_params)
now = int(time.time() * 1000)
str_to_sign = str(now) + 'POST' + '/api/v1/orders' + json_params
signature = base64.b64encode(hmac.new(api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
passphrase = base64.b64encode(hmac.new(api_secret.encode('utf-8'), api_passphrase.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": signature,
"KC-API-TIMESTAMP": str(now),
"KC-API-KEY": api_key,
"KC-API-PASSPHRASE": passphrase,
"KC-API-KEY-VERSION": "2",
"Content-Type": "application/json"
}
response = requests.request('POST', future_base_url + '/api/v1/orders', params=params, headers=headers)
print(response.text)

This worked for me:
tickerK = "AVAXUSDTM"
clientOid = tickerK + '_' + str(now)
side = "buy"
typee = "market"
leverage = "2"
stop = "up"
stopPriceType = "TP"
stopPrice = "12"
size = "3"
# Set the request body
data = {
"clientOid":clientOid,
"side":side,
"symbol":tickerK,
"type":typee,
"leverage":leverage,
"stop":stop,
"stopPriceType":stopPriceType,
"stopPrice":stopPrice,
"size":size
}
data_json = json.dumps(data, separators=(',', ':'))
data_json
url = 'https://api-futures.kucoin.com/api/v1/orders'
now = int(time() * 1000)
str_to_sign = str(now) + 'POST' + '/api/v1/orders' + data_json
signature = base64.b64encode(
hmac.new(api_secret.encode('utf-8'), str_to_sign.encode('utf-8'), hashlib.sha256).digest())
passphrase = base64.b64encode(hmac.new(api_secret.encode('utf-8'), api_passphrase.encode('utf-8'), hashlib.sha256).digest())
headers = {
"KC-API-SIGN": signature,
"KC-API-TIMESTAMP": str(now),
"KC-API-KEY": api_key,
"KC-API-PASSPHRASE": passphrase,
"KC-API-KEY-VERSION": "2",
"Content-Type": "application/json"
}
# Send the POST request
response = requests.request('post', url, headers=headers, data=data_json)
# Print the response
print(response.json())
Please take care of the lines marked in red:
Remove spaces from the json
Add the json to the string to sign
Add content type to the header
Do the request this way

Related

POST users import v2 internal server error

I am working on a fully automatic pipeline for my company where we automatically set up projects, add users and upload files with the different APIs on BIM360. On the stage of adding a user I get a 500 internal server error:
{"code":2000,"message":"no implicit conversion of String into Integer"}
We are using a two-legged authentication approach and as such the header looks like this:
Authorization: Bearer <token> (It has account:write rights)
x-user-id: ************ (uid of my admin account)
Content-Type: application/json
The request content is this:
#"{
""email"": """ + ***#********.** + #""",
""services"": {
""document_management"": {
""access_level"": """ + admin+ #"""
},
""project_administration"": {
""access_level"": """ + admin+ #"""
}
},
""industry_roles"": []}";
I just can't quite seem to figure out what I am doing wrong. Hope someone can help me.
EDIT: Full code for this request
public async static Task<HttpStatusCode> AddUserToProjectEmail(string projectId, string accountId, string accessToken, string userToAddEmail, string userPrivilege, string adminUserId)
{
using (HttpClient httpClient = new HttpClient())
{
using (HttpRequestMessage request = new HttpRequestMessage())
{
//Documentation for what to put in the Http POST: https://forge.autodesk.com/en/docs/bim360/v1/reference/http/projects-project_id-users-import-POST/
request.Method = new HttpMethod("POST");
request.RequestUri = new Uri("https://developer.api.autodesk.com/hq/v2/regions/eu/accounts/" + accountId + "/projects/" + projectId + "/users/import");
//Make the request payload
string jsonPayload = AddPayloadToUserAddEmail(userToAddEmail, userPrivilege);
request.Content = new StringContent(jsonPayload);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
request.Headers.Add("x-user-id", adminUserId);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
//Send request
var response = await httpClient.SendAsync(request);
return response.StatusCode;
}
}
}
And the request payload method:
private static string AddPayloadToUserAddEmail(string userToAddEmail, string userPrivilege)
{
string payload = #"{
""email"": """ + userToAddEmail + #""",
""services"": {
""project_administration"": {
""access_level"": """ + userPrivilege + #"""
},
""document_management"": {
""access_level"": """ + userPrivilege + #"""
}
},
""industry_roles"": []
}";
return payload;
}
I have checked all the IDs through the URL on BIM360, however it's not possible to check the Uid of my account I think.
EDIT 2: I should note that I was getting a different error before I added the x-user-id header, where it just said forbidden which makes sense. This lead me to think it had something to do with the x-user-id header, but I can't figure it out.
Don't be like me and forget to wrap the payload into an array as stated on the docs that it has to be. Using this as payload worked
#"[{
""email"": """ + userToAddEmail + #""",
""services"": {
""project_administration"": {
""access_level"": """ + userPrivilege + #"""
},
""document_management"": {
""access_level"": """ + userPrivilege + #"""
}
},
""industry_roles"": []
}]";

JSON.Lua json.encode return nil

I'm new to LUA and tried learning coding this language with Garrys Mod.
I want to get the messages from the Garrys Mod chat and send them into a Discord channel with a webhook.
It works, but I tried expanding this project with embeded messages. I need JSON for this and used json.lua as a library.
But as soon as I send a message I retrieve the following error message:
attempt to index global 'json' (a nil value)
The code that causes the error is the following:
json.encode({ {
["embeds"] = {
["description"] = text,
["author"] = {
["name"] = ply:Nick()
},
},
} }),
The complete code:
AddCSLuaFile()
json = require("json")
webhookURL = "https://discordapp.com/api/webhooks/XXX"
local DiscordWebhook = DiscordWebhook or {}
hook.Add( "PlayerSay", "SendMsg", function( ply, text )
t_post = {
content = json.encode({ {
["embeds"] = {
["description"] = text,
["author"] = {
["name"] = ply:Nick()
},
},
} }),
username = "Log",
}
http.Post(webhookURL, t_post)
end )
I hope somebody can help me
Garry's Mod does provide two functions to work with json.
They are:
util.TableToJSON( table table, boolean prettyPrint=false )
and
util.JSONToTable( string json )
There is no need to import json and if I recall correctly it isn't even possible.
For what you want to do you need to build your arguments as a table like this:
local arguments = {
["key"] = "Some value",
["42"] = "Not always the answer",
["deeper"] = {
["my_age"] = 22,
["my_name"] = getMyName()
},
["even more"] = from_some_variable
and then call
local args_as_json = util.TableToJSON(arguments)
Now you can pass args_as_json to your
http.Post( string url, table parameters, function onSuccess=nil, function onFailure=nil, table headers={} )

How to post json in lua using cURL

I'm trying to post json in Lua using cURL. I can't find any example online.
Something like this:
c = curl.easy{
url = "http://posttestserver.com/post.php",
-- url = "http://httpbin.org/post",
post = true,
httppost = curl.form{
data = "{}",
type = "application/json",
},
}
t = {}
c:perform{
writefunction = function(s)
t[#t+1] = s
end
}
c:close()
Try this one.
local cURL = require "cURL"
c = cURL.easy{
url = "http://posttestserver.com/post.php",
post = true,
httpheader = {
"Content-Type: application/json";
};
postfields = "{}";
}
c:perform()

Json Parse Unexpected token with node

I am getting a strange unexpected token error trying to parse a JSON file using node. I have tested the code with 2 files that look identical. I used a code compare tool to do a comparison and they do appear identical. However, when I try to parse them, one gets the error and the other does not. The file that does not work is being generated from a PowerShell script. The one that does work was manually created. I am baffled. One thing I noticed that is different about them when I write the json out to the console is, the one that does not work has a ? at the beginning.
The json from the file that does not work:
data = ?{ "stack_name": "perf-a", "parameters": { "StackSet": "b", "MonitoringEnableAutoscalingAlarm": "True", "MachineConfigEnvironment": "Perf", "AppEnvironmentType": "perf", "StackInRotation": "True", "MonitoringEnableNotificationOnlyAlarms": "False", "AMIImage": "ami-123456789" }, "tags": { "CostCenter": "12345", "Owner": "test#test.com" }, "cft_file":
"cft/cft.json"}
The json from the file that does work:
data = { "stack_name": "perf-a", "parameters": { "StackSet": "a", "MonitoringEnableAutoscalingAlarm": "True", "MachineConfigEnvironment": "Perf", "AppEnvironmentType": "perf", "StackInRotation": "True", "MonitoringEnableNotificationOnlyAlarms": "False", "AMIImage": "ami-123456789" }, "tags": { "CostCenter": "45229", "Owner": "test#test.com" }, "cft_file": "
cft/cft.json"}
The code I am using for testing is:
var envFile = "perf2.json";
var fs = require('fs');
console.log('envFile = ' + envFile);
fs.readFile(envFile, 'utf8', function (err, data) {
if (err) {
console.log('error reading variables file');
throw err;
}
try {
var JsonData = JSON.stringify(data);
console.log('JsonData = ' + JsonData);
data = data.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f")
.replace(/\\0/g, "")
.replace(/\\v/g, "")
.replace(/\\e/g, "\\e");
data = data.replace(/[\u0000-\u001F]+/g, "");
console.log('data = ' + data);
var cftVariables = JSON.parse(data);
console.log('cftVariables = ' + cftVariables);
console.log('cftVariables stack name = ' + cftVariables.stack_name);
} catch (e) {
console.log('error parsing variables file');
throw e;
}
});
As you can see, I have also tried JSON.stringify but I lose the properties and cftVariables.stack_name becomes undefined.
This problem has been plaguing me for several days and I am now at a loss as to how to fix it.
For reference, here is the snippet of PowerShell that creates the file. The problem might be there.
$savePath = "envs/" +$filetouse + ".json"
$parameters = #{AppEnvironmentType =$AppEnvironmentType;
StackSet = $StackSet;
StackInRotation = $StackInRotation;
AMIImage = $amiid;
MonitoringEnableAutoscalingAlarm = $MonitoringEnableAutoscalingAlarm;
MonitoringEnableNotificationOnlyAlarms= $MonitoringEnableNotificationOnlyAlarms;
MachineConfigEnvironment = $MachineConfigEnvironment;
}
$tags = #{Owner = "test#test.com";
CostCenter = "45229";
}
$envcft = #{stack_name =$stack_name;
cft_file = "cft/cft.json";
parameters = $parameters;
tags = $tags;
} | ConvertTo-Json
Write-host("Saving the env file with the new amiId... ")
$envcft | Out-File $savePath -Encoding UTF8 -force
Assuming you are reading the data in from a file, once you have the string you can use the remove function to get rid of that "?".
Something like this:
s = s.replace('?','');
EDIT
since the replace did not work, try 1) either not specifying an encoding when you save the file, or 2) specify UTF16

Urban Airship API V3 Push request - 400 Bad request

I am getting 400 - Bad request.
This is my request:
{
"audience" : {
"tags": ["994c4298-89ba-4715-879d-10540fcf0059","a82e8789-3239-4899-b6dc-1e6a71dc06d4"]
},
"notification": {
"alert": "19 Aug Test",
"extra": {"NewsID":"127"}
},
"device_types": "all"
}
This is my code:
using (var client = new WebClient())
string PostData = "I am assigining above json string here";
UTF8Encoding encoding = new UTF8Encoding();
var dataToPost = encoding.GetBytes(PostData);
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers.Add(HttpRequestHeader.Accept,"application/vnd.urbanairship+json; version=3;");
//client.Headers[HttpRequestHeader.Accept] = "application/vnd.urbanairship+json; version=3";
client.Credentials = new NetworkCredential("App key", "Master key");
var result = client.UploadData("https://go.urbanairship.com/api/push/", "POST", dataToPost);
Stream stream = new MemoryStream(result);
StreamReader reader = new StreamReader(stream);
string text = reader.ReadToEnd();
Worked when I changed "tags" to "tag" and put "extra" in "ios": {"extra": "blah blah blah"}
I think they have made these changes in V3.
Thanks.