Binance API Withdrawal Error: "Signature for this request is not valid." - binance

I'm facing an issue with the Binance API
Whenever I try to make a request for withdrawal, it returns "Signature for this request is not valid." error message, even though if with the same function I make a request for the account info, Funding balance, getAll balances or whatever, it works.
I already tried several solutions, but nothing seemed to work. This are some of my tries reading similar issues
Works with endpoints like "api/v3/account" or "sapi/v1/capital/config/getall"
Sending the signature and the params in the body (it returns "You are not authorized to execute this request" error message, I think is because is not reading the body, only query params)
Activate all permissions for the API, and check the API
Send in the query the param "name"
Using Node packages like node-binance-api (It's not up to date with the request for withdrawals)
Changing scripts in librery node-binance-api to the actual api for withdrawals (same error as doing it myself)
I'm using NodeJs, axios to make the requests. This is my function:
/**
* Send Request to withdraw USDT funds from the selected wallet to a specified address
* #param wallet
* #param amount
* #param address
* #returns
* #link https://binance-docs.github.io/apidocs/spot/en/#withdraw-user_data
*/
makeWithdrawal(
wallet: WalletType = 'SPOT',
amount: number,
address: string
) {
const walletIndex = WalletEnum[wallet];
return this.makeRequest<{ id: string }>(
'sapi/v1/capital/withdraw/apply',
'POST',
{
coin: 'USDT',
amount,
wallet: walletIndex,
address,
network: 'TRX',
name: '_'
}
);
}
/**
* Makes Request to Binance Pay API
* #param endpoint
* #param method
* #param params
* #returns
* #link https://binance-docs.github.io/apidocs/spot/en
*/
private makeRequest<T>(
endpoint: string,
method: Method = 'GET',
params: {[key: string]: string | number} = {}
): Promise<T> {
const timestamp = Number(new Date().getTime()).toFixed(0);
let query = `timestamp=${timestamp}`;
for (const key in params) {
if (Object.prototype.hasOwnProperty.call(params, key)) {
const value = params[key];
query += `&${key}=${value}`
}
}
const signature = this.sign(query);
const headers: AxiosRequestHeaders = {
'X-MBX-APIKEY': process.env.BINANCE_API_KEY,
};
const requestObservable = this.httpService.request<T>({
method,
url: `${process.env.BINANCE_API_URL}/${endpoint}`,
params: {...params, timestamp, signature},
headers
}).pipe(
map(res => res.data)
);
return lastValueFrom(requestObservable);
}
/**
* Signs payload with private key
* #param payload
* #returns
*/
private sign(query: string) {
return createHmac('sha256', process.env.BINANCE_API_SECRET)
.update(query)
.digest('hex');
}
I really can't understand what is going, if someone could please help me to solve this, as I'm reading this is a common issue, but I really tried solutions and no hope.
Thank you

For anyone having this problem, the issue was that I was sending the request inside the "params" instead of the url, weirdly enough, it didn't proccess it correctly, so make this small change:
const requestObservable = this.httpService.request<T>({
method,
url: `${process.env.BINANCE_API_URL}/${endpoint}?${query}&signature=${signature}`,
headers
}).pipe(
map(res => res.data)
);
And you are good to go

Related

Function implementation is missing or not immediately following the declaration

hi everyone im new to typescript and node and trying to make a chat app using stream.io and typescript. Now im trying to get all messagess from a specific channell in getallmessages function. however when i call this function to test it im getting error saying Function implementation is missing or not immediately following the declaration. Can someone please tell me how i can call this function so i can display response to console ? thanks !
import { StreamChat } from 'stream-chat';
import { appConfig } from '#/config';
export class ChatService {
public static masterHealthBotUserId = 'masterHealthBot';
private static client = StreamChat.getInstance(
appConfig.get('getstream').apiKey,
appConfig.get('getstream').apiSecret,
);
/**
* Creates get stream chat token that can be used by the client to connect to getStream
* #param userId - User Id
* #param expiry - expiration time of token. If undefined then token wont expire
*/
public createToken({ userId, expiry }: { userId: number; expiry?: number }) {
return ChatService.client.createToken(userId.toString(), expiry);
}
// function that im trying to call but its giving me error
public async getallmessages(podId: string) {
const channel = ChatService.client.channel('messaging', podId);
const messageFilter = { id: { $exists: true } };
const response = await channel.search(messageFilter);
console.log(response.results);
}}
}
getallmessages('3');
}

How to add IBM API authentication to my code?

Watson Assistant only supports one Webhook url. The issue is I have multiple nodes in Assistant that need to call different "Actions" I have hosted in IBM Cloud Functions. How can I do that? I tried to code and "Action" that uses the NPM Axios to call the other "Actions" but it fails as it lacks authentication.
Can someone tell me how to do it? I need the BASE URL to be athenticated via my IBM Cloud user API to grant access to my namespace.
this is the action I created that acts as a "Dispatch" for webhooks for Watson Assistant.
/**
*
* main() will be run when you invoke this action
*
* #param Cloud Functions actions accept a single parameter, which must be a JSON object.
*
* #return The output of this action, which must be a JSON object.
*
*
* Version: 1.5 beta (API HUB)
* Date: 24/04/2020
*
*/
const axios = require("axios");
// Change to your "BASE_URL". Type in the "Web Action" url without the name of it at the end. (must NOT contains the end '/')
// All "Actions" must be within the same namespace.
const BASE_URL = "https://jp-tok.functions.cloud.ibm.com/api/v1/web/
const POST = "post";
const GET = "get";
const ANY = "any";
const ALL = "all";
/* List all your API methods
1. method - API Name (This is the "Actions" name at the end of the Web Action URL or just the name)
2. attr - Attributes that should be available in the params object
3. rule - Currently supports 2 rules;
a) any - params is valid if "any" of the attributes are present
b) all - params is valid only if all attributes are present
4. httpmethod -Supports "POST" and "GET"
5. contains - Use for validating GET URL parameters
*/
const API_METHODS = [{
method: "Emails", // Change to your API method "Please put the function name located at the end of the url without "/" example "Email"
attr: ["client_email", "department_email"],
rule: ANY,
httpmethod: POST,
contains: null
},
{
method: "testapi", // If Watson needs to "GET" information to a user or athenticate a user
attr: [],
rule: ALL,
httpmethod: GET,
contains: "?ID="
},
]
// Returns true if the "params" is valid for the given API method
function isValidParam(method, params = {}) {
var attributes = [];
attributes = method.attr;
var isAny = method.rule === ANY;
for (let index = 0; index < attributes.length; index++) {
const attr = attributes[index];
if (isAny) {
if (Object.hasOwnProperty.call(params, attr)) {
return true;
}
} else {
if (!Object.hasOwnProperty.call(params, attr)) {
return false;
}
}
}
if (attributes.length === 0 && method.contains) {
return (JSON.stringify(params).indexOf(method.contains) > -1)
}
// if the code reaches this position, inverse of "isAny" should return the actual validation status.
return !isAny;
}
async function main(params) {
var result = [];
// Stop on first failure
// We iterate through all API methods. Because there can be more than one matching API for the given param type
for (let index = 0; index < API_METHODS.length; index++) {
const apiMethod = API_METHODS[index];
const url = BASE_URL + '/' + apiMethod.method;
if (isValidParam(apiMethod, params)) {
let response = apiMethod.httpmethod === POST ?
await axios.post(url, params) :
await axios.get(url + params); // Expects the parameter to be a string in this case like '?id=345343'
console.log(response);
result.push({
sent: true,
url: url,
request: params,
});
}
}
return {
sent: true,
details: result
};
}
// THe part of the code that needs to be copied to call other functions within the namespace.
/* const API_METHODS = [{
method: "Emails", // Change to your API method "Please put the function name located at the end of the url without "/" example "Email"
* attr: ["bamboo_email", "latitude_email", "latest_r_email", "department_email"],
rule: ANY,
httpmethod: POST,
contains: null
},
{
method: "testapi", // If Watson needs to "GET" information to a user or athenticate a user
attr: [],
rule: ALL,
httpmethod: GET,
contains: "?ID="
},
] */
When I run it in Watson Assistant I get the following error:
Webhook call response body exceeded [1050000] byte limit.response code: 200, request duration: 591, workspace_id: 150088ee-4e86-48f5-afd5-5b4e99d171f8, transaction_id: a8fca023d456d1113e05aaf1f59b1b2b, url_called: https://watson-url-fetch.watson-url-fetcher:443/post?url=https%3A%2F%2Fjp-tok.functions.cloud.ibm.com%2Fapi%2Fv1%2Fweb%2F23d61581-fa68-4979-afa2-0216c17c1b29%2FWatson+Assistant%2FAssistant+Dispatch.json (and there is 1 more error in the log)

Sending Emails with Gmail API

I'm currently working on hooking into the Gmail API using NodeJS. I have a working connection and can access my messages and such, but I'm having difficulty actually sending email with the API. Here is what I have below:
/**
* Send Message.
*
* #param {String} userId User's email address. The special value 'me'
* can be used to indicate the authenticated user.
* #param {String} email RFC 5322 formatted String.
* #param {Function} callback Function to call when the request is complete.
*/
function sendMessage(userId, email, callback, auth) {
// Using the js-base64 library for encoding:
// https://www.npmjs.com/package/js-base64
//var base64EncodedEmail = Base64.encodeURI(email);
var base64EncodedEmail = Buffer.from(email).toString('base64');
var request = gapi.client.gmail.users.messages.send({
'userId': userId,
'resource': {
'raw': base64EncodedEmail
}
});
request.execute(callback);
}
This is from the official documentation (here), for the most part. I'm calling the function as such:
authorize(JSON.parse(content), sendMessage('me', btoa('This is a test')));
The error I'm getting is this:
var request = gapi.client.gmail.users.messages.send({
^
ReferenceError: gapi is not defined
at sendMessage (D:\Documents\Web Programming\React\neis-guy-painting\src\Server\Node\gmail.js:148:17)
at fs.readFile (D:\Documents\Web Programming\React\neis-guy-painting\src\Server\Node\gmail.js:23:34)
at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)
I realize that this is because I don't have gapi defined, but I can't seem to figure out what that actually should be.
What am I missing here?

Twilio - Incoming calls not being processed (quickstart)

I've sign up to start using Twilio and I'm trying to setup the quickstart (https://www.twilio.com/docs/voice/client/javascript/quickstart) and it's almost working but incoming calls are not being received by:
Client code (used on browser after getTokenCapabilities):
Twilio.Device.incoming(function (conn) {
log('Incoming connection from ' + conn.parameters.From);
var archEnemyPhoneNumber = '+12093373517';
if (conn.parameters.From === archEnemyPhoneNumber) {
conn.reject();
log('It\'s your nemesis. Rejected call.');
} else {
// accept the incoming connection and start two-way audio
conn.accept();
}
});
Code on Twilio Function for voice calls (consoles are always printed and else condition is never called:
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
console.log('entrou aqui');
if(event.To) {
console.log('entrou ali');
// Wrap the phone number or client name in the appropriate TwiML verb
// if is a valid phone number
const attr = isAValidPhoneNumber(event.To) ? 'number' : 'client';
const dial = twiml.dial({
callerId: context.CALLER_ID,
});
dial[attr]({}, event.To);
} else {
twiml.say('Thanks for calling!');
}
console.log('callback');
callback(null, twiml);
};
/**
* Checks if the given value is valid as phone number
* #param {Number|String} number
* #return {Boolean}
*/
function isAValidPhoneNumber(number) {
return /^[\d\+\-\(\) ]+$/.test(number);
}
I've include my phone number as Verified Caller ID, got a number from Twilio and create the functions using template Twilio Client Quickstart.
On Twilio Client Quickstart, i've paste TwiML SID as TWIML_APP_SID and tried to use my phone number and the number from Twilio as CALLER_ID.
Also I've changed VOICE URL on TwiML configuration and changed the VOICE URL on phone number from twilio configuration.
Any ideas on what is missing or what is wrong? When I open on browser http://127.0.0.1:8080/, It's possible to make calls but I don't receive any call on browser when I call to twilio number.
In order to answer call, you need to have your token name identity in a tag in your VoiceResponse, here is an example.
exports.incomingVoiceResponse = function voiceResponse( to ) {
// Create a TwiML voice response
const twiml = new VoiceResponse();
// Wrap the phone number or client name in the appropriate TwiML verb
// if is a valid phone number
const attr = isAValidPhoneNumber(to) ? 'client' : 'number';
const dial = twiml.dial({
callerId: to,
});
dial[attr]({}, 'jesus');
console.log(twiml.toString())
return twiml.toString();
};
See the 'jesus' client tag I have put ? Here is the token generator side :
exports.tokenGenerator = function tokenGenerator() {
const identity = 'jesus';
const capability = new ClientCapability({
accountSid: config.accountSid,
authToken: config.authToken,
});
capability.addScope(new ClientCapability.IncomingClientScope(identity));
capability.addScope(new ClientCapability.OutgoingClientScope({
applicationSid: config.twimlAppSid,
clientName: identity,
}));
// Include identity and token in a JSON response
return {
identity: identity,
token: capability.toJwt(),
};
};
This works for me using the node quickstart as is and changing both of these functions.
However, don't forger to change the from 'number' to 'client' in function voiceResponse because it's an incoming call and not an outgoing.
const attr = isAValidPhoneNumber(to) ? 'client' : 'number';
instead of
const attr = isAValidPhoneNumber(to) ? 'number' : 'client';
Since the default nameGenerator from the client-quickstart-node from Twilio generates a random name, it isn't properly set when receiving incoming call.

usage example of "sendDirectlyToAll" of simplewebrtc?

I am trying to send text to all my peers and I found this function "sendDirectlyToAll".
For your convenience, I put the function information here:
sendDirectlyToAll(channelLabel, messageType, payload) - broadcasts a
message to all peers in the room via a dataChannel.
string channelLabel - the label for the dataChannel to send on.
string messageType - the key for the type of message being sent.
object payload - an arbitrary value or object to send to peers.
I do not understand the meaning of 2nd and 3rd parameters. Could you kindly show me an example how to use this function?
Thanks
Derek
Here is my example showing how i managed to get it working:
/**
* send directly to all other peers
*/
oSimpleWebRTC.sendDirectlyToAll(
'meta', // sLabel
'info', // sType - will become oData.sType
{"foo": "bar"} // oData - will become oData.payload
);
/**
* Handle incoming dataChannel messages sent by "sendDirectlyToAll"
* #param {object} oPeer The Remote sending Peer Object
* #param {string} sLabel A Label, e.g.: 'meta'
* #param {object} oData Object containing the relevant Data
*/
oSimpleWebRTC.on('channelMessage', function (oPeer, sLabel, oData) {
// e.g. we want label "hark" to be ignored, as it fires continiously.
if ('hark' === sLabel) {
return true;
}
if ('meta' === sLabel) {
if ('info' === oData.type)
{
// do your stuff
console.log(oData.payload.foo);
}
}
}
Also, There are Answers to this question at the official SimpleWebRTC issues Tracker: https://github.com/andyet/SimpleWebRTC/issues/450
See my blog post to this example: https://blog.ueffing.net/post/2017/02/22/simplewebrtc-usage-example-of-senddirectlytoall/

Resources