Post trade Order Binance Signature error - ios

I am trying to make trade using binance api from ios.
Always gives error ["code": -1022, "msg": Signature for this request is not valid.]
Code:
public override func requestFor(api: APIType) -> NSMutableURLRequest {
let mutableURLRequest = api.mutableRequest
if let key = key, let secret = secret, api.authenticated {
var postData = api.postData
//postData["symbol"] = "BNBBTC"
//postData["timestamp"] = "\(Int(Date().timeIntervalSince1970 * 1000))"
postData["symbol"] = "BNBBTC"
postData["side"] = "SELL"
postData["type"] = "MARKET"
postData["recvWindow"] = "5000"
postData["quantity"] = "0.1"
postData["timestamp"] = "\(Int(Date().timeIntervalSince1970 * 1000))"
if let hmac_sha = try? HMAC(key: secret, variant: .sha256).authenticate(Array(postData.queryString.utf8)) {
let signature = Data(bytes: hmac_sha).toHexString()
postData["signature"] = signature
}
var postDataString = ""
if let data = postData.data, let string = data.string, postData.count > 0 {
postDataString = string
if case .GET = api.httpMethod {
mutableURLRequest.httpBody = data
} else if case .POST = api.httpMethod {
var urlString = mutableURLRequest.url?.absoluteString
urlString?.append("?")
urlString?.append(postData.queryString)
let url = URL(string: urlString!)
mutableURLRequest.url = url
}
api.print("Request Data: \(postDataString)", content: .response)
}
mutableURLRequest.setValue(key, forHTTPHeaderField: "X-MBX-APIKEY")
}
return mutableURLRequest
}
Edit: While using account api i am not facing any issues with the signature. It gives response as expected

I had same ... problem and I found answer. When you generate signature, inputs for Test Order and Account Info are different.
Inputs for account info:
string input = "timestamp=1535623795177";
string apiSecret = "YOUR API SECRET"
Inputs for test limit order:
string input = "symbol=ETHBTC&side=BUY&recvWindow=6500&type=LIMIT&timeInForce=GTC&quantity=100&price=0.1&timestamp=1535623795177";
string apiSecret = "YOUR API SECRET"
and generate signature working example (C#):
private string GenerateSignature(string input, string apiSecret)
{
var encoding = new UTF8Encoding();
byte[] keyByte = encoding.GetBytes(apiSecret);
byte[] messageBytes = encoding.GetBytes(input);
using (var hmacsha256 = new HMACSHA256(keyByte))
{
byte[] hashMessage = hmacsha256.ComputeHash(messageBytes);
return String.Concat(hashMessage.Select(b => b.ToString("x2")));
}
}

Related

Bad request when posting to OData Data Entity in Dynamics 365

I've created a public Data Entity in dynamics with the following fields:
I keep getting a bad request response, but I'm not sure why.
I've tried to make a POST request in two ways:
1.
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionStatus = "Created" };
string jsonMessage = JsonConvert.SerializeObject(hireAction);
using (HttpClient client = new HttpClient())
{
HttpRequestMessage requestMessage = new
HttpRequestMessage(HttpMethod.Post, "MyDynamicsEnvironmentName/data/HireActions?cross-company=true");
requestMessage.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
requestMessage.Headers.Add("Authorization", AuthResult.AuthorizationHeader);
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//Logic
}
}
var url = "MyDynamicsEnvironmentName/data/HireActions?cross-company=true";
var req = HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
req.Headers["Authorization"] = AuthResult.AuthorizationHeader;
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionId = "12345", HireActionStatus = "Created" };
var jsonSettings = new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
var postString = "CompanyName='DEMF'" + "&MovieId='DEMF-000000014'" + "&HireActionId=132&HireActionStatus='Created'";
var data = JsonConvert.SerializeObject(postString, jsonSettings);
var bytes = Encoding.Default.GetBytes(postString);
var newStream = req.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
using (var resp = req.GetResponse())
{
var results = new StreamReader(resp.GetResponseStream()).ReadToEnd();
}
Some keypoints:
-Of course you'd replace MyDynamicsEnvironmentName with the URL for the environment. The URL is correct and verified however, by the fact that GET requests do work
-The Authresult.AuthorizationHeader contains a valid token, also validated by working GET requests
As said before, both of these result in a bad request. Does someone know what is wrong or missing?

Using webforms with API - returns null values

Can anybody help me?
This code work fine with no parameter:
private void PopulateGridView()
{
string apiUrl = apiurl + "local_stud_listgrupmenu";
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Encoding = Encoding.UTF8;
string json2 = client.UploadString(apiUrl,"POST");
Response.Write("output:" + json2.ToString());
}
but this code below return null with post parameter, what wrong my code :)
private void crudinsert()
{
string data;
string apiUrl = apiurl + "ins_rec_crudparentmenu";
string x = "";
var vm = new { mod = "0", moduldesc ="test'", modulurl = "tesx.aspx", idparent= "0" };
using (var clien2 = new WebClient())
{
var dataString = (new JavaScriptSerializer()).Serialize(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
x = client.UploadString(new Uri(apiUrl), "POST", dataString);
}
Response.Write("output:"+x);
}

Alamofire request not sending post parameter

I am trying to create an Alamofire request as follows:
//creating parameters for the post request
let parameters: Parameters=[
"modelo": modelo_id
]
let url_dispo = URL(string: "https://../calcular_precio.php")
Alamofire.request(url_dispo!, method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
//to get status code
if let status = response.response?.statusCode {
switch(status){
case 201:
print("example success")
default:
print("error with response status: \(status)")
}
}
//to get JSON return value
if let result = response.result.value {
let JSON = result as! NSDictionary
print(JSON)
}
}
My issue is that the response from the url is telling me that the post parameter is not sended with the request.
I have checked the value for modelo_id and it is correct.
Is there anything wrong in my code?
Here you have the complete PHP script:
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['modelo']) ) {
// receiving the post params
$modelo= $_POST['modelo'];
// get the user by email and password
$user = $db->getPrecioByModelo($modelo);
if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["id"] = $user["id"];
$response["precio"]["p1"] = $user["p1"];
$response["precio"]["p2"] = $user["p2"];
$response["precio"]["p3"] = $user["p3"];
$response["precio"]["p4"] = $user["p4"];
$response["precio"]["p5"] = $user["p5"];
$response["precio"]["p6"] = $user["p6"];
$response["precio"]["p7"] = $user["p7"];
$response["precio"]["p8"] = $user["p8"];
$response["precio"]["p9"] = $user["p9"];
$response["precio"]["p10"] = $user["p10"];
$response["precio"]["p11"] = $user["p11"];
$response["precio"]["p12"] = $user["p12"];
$response["precio"]["p13"] = $user["p13"];
$response["precio"]["p14"] = $user["p14"];
$response["precio"]["p15"] = $user["p15"];
$response["precio"]["p16"] = $user["p16"];
$response["precio"]["p17"] = $user["p17"];
$response["precio"]["p18"] = $user["p18"];
$response["precio"]["p19"] = $user["p19"];
$response["precio"]["p20"] = $user["p20"];
$response["precio"]["p21"] = $user["p21"];
$response["precio"]["p22"] = $user["p22"];
$response["precio"]["p23"] = $user["p23"];
echo json_encode($response);
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Wrong action! Please, try again!";
echo json_encode($response);
}
} else {
// required post params is missing
$response["error"] = TRUE;
$response["modelo"] = $modelo;
$response["error_msg"] = "Required parameters missing!";
echo json_encode($response);
}
?>
EDIT:
Here you have the debugger output:
modeloid 1069
SUCCESS: {
error = 1;
"error_msg" = "Required parameters email or password is missing!";
modelo = "<null>";
}
error with response status: 200
{
error = 1;
"error_msg" = "Required parameters email or password is missing!";
modelo = "<null>";
}
The problem is that you are sending the data with Alamofire using
JSONEncoding.default
and expecting your data on the backend as URL encoding. Change the encoding to:
URLEncoding.default
and you should be good to go.

I am writing 3DES (using SHA1 HASH) encryption algorithm using C #. Key size error

I am writing 3DES (using SHA1 HASH) encryption algorithm using C #.
Size error in tdes.Key = keyArray of the following code. I do not know what went wrong.
public static string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();
// Get the key from config file
string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
//System.Windows.Forms.MessageBox.Show(key);
if (useHashing)
{
SHA1CryptoServiceProvider objSHA1CryptoService = new SHA1CryptoServiceProvider();
keyArray = objSHA1CryptoService.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
objSHA1CryptoService.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
}

Getting error while using DocuSign in DotNet application

I am implementing the DocuSign functionality in my application to sign the PDF.
I am following the below link:
https://www.docusign.com/developer-center/api-overview
We are able to add signature in the PDF while using the steps mentioned in the above link but while calling the same method for second time to signed a new PDF we are getting error message at the line of CreateEnvelope()
Error Response: { "errorCode": "UNSPECIFIED_ERROR", "message":
"Input string was not in a correct format." }
it generate an error while Creating envelop. at this line
EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);
Below is the code which i use
static string userName = Utility.GetConfigValue("docSignUserName");
static string password = Utility.GetConfigValue("docSignPassword");
static string integratorKey = Utility.GetConfigValue("docSignIntegratorKey");
static string baseURL = "";
public static SignedPDF SignDocument(UserViewModel user, StateViewModel state, string signFilePath, string newFilePath, string controlSign)
{
PdfReader pdfReader = new PdfReader(signFilePath);
PdfReader newpdfReader = new PdfReader(newFilePath);
PdfStamper pdfStamper = new PdfStamper(newpdfReader, new FileStream(HttpContext.Current.Server.MapPath(Utility.GetConfigValue("StateTaxForms")) + "Test.pdf", FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
IList<AcroFields.FieldPosition> fieldPositions = pdfFormFields.GetFieldPositions(controlSign);
try
{
AcroFields.FieldPosition fieldPosition = fieldPositions[0];
// Enter recipient (signer) name and email address
string recipientName = user.FirstName + " " + user.LastName;
string recipientEmail = user.Email;
// instantiate api client with appropriate environment (for production change to www.docusign.net/restapi)
string basePath = Utility.GetConfigValue("docSignInstantiateClient");
// instantiate a new api client
ApiClient apiClient = new ApiClient(basePath);
// set client in global config so we don't need to pass it to each API object
Configuration.Default.ApiClient = apiClient;
string authHeader = "{\"Username\":\"" + userName + "\", \"Password\":\"" + password + "\", \"IntegratorKey\":\"" + integratorKey + "\"}";
Configuration.Default.AddDefaultHeader("X-DocuSign-Authentication", authHeader);
// we will retrieve this from the login() results
string accountId = null;
// the authentication api uses the apiClient (and X-DocuSign-Authentication header) that are set in Configuration object
AuthenticationApi authApi = new AuthenticationApi();
LoginInformation loginInfo = authApi.Login();
// user might be a member of multiple accounts
accountId = loginInfo.LoginAccounts[0].AccountId;
// Read a file from disk to use as a document
byte[] fileBytes = File.ReadAllBytes(signFilePath);
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.EmailSubject = "Please sign this document";
// Add a document to the envelope
Document doc = new Document();
doc.DocumentBase64 = System.Convert.ToBase64String(fileBytes);
doc.Name = "SignedFile.pdf";
doc.DocumentId = "1";
envDef.Documents = new List<Document>();
envDef.Documents.Add(doc);
// Add a recipient to sign the documeent
Signer signer = new Signer();
signer.Name = recipientName;
signer.Email = recipientEmail;
signer.RecipientId = "1";
// must set |clientUserId| to embed the recipient
signer.ClientUserId = "1234";
// Create a |SignHere| tab somewhere on the document for the recipient to sign
signer.Tabs = new Tabs();
signer.Tabs.SignHereTabs = new List<SignHere>();
SignHere signHere = new SignHere();
var height = pdfReader.GetPageSize(1).Height;
signHere.DocumentId = "1";
signHere.RecipientId = "1";
signHere.PageNumber = Convert.ToInt32(fieldPosition.page).ToString();
signHere.XPosition = Convert.ToInt32(fieldPosition.position.Left).ToString();
if (state.Abbreviation == "DC" && controlSign != "Signature of Employee")
{
signHere.YPosition = (height - Convert.ToInt32(fieldPosition.position.Top - 5)).ToString();
}
else
{
signHere.YPosition = (height - Convert.ToInt32(fieldPosition.position.Top + 35)).ToString();
}
if (state.Abbreviation == "NC" && controlSign != "Signature of Employee")
{
signHere.YPosition = (height - Convert.ToInt32(fieldPosition.position.Top + 25)).ToString();
}
signer.Tabs.SignHereTabs.Add(signHere);
envDef.Recipients = new Recipients();
envDef.Recipients.Signers = new List<Signer>();
envDef.Recipients.Signers.Add(signer);
// set envelope status to "sent" to immediately send the signature request
envDef.Status = "sent";
// Use the EnvelopesApi to create and send the signature request
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.CreateEnvelope(accountId, envDef);
RecipientViewRequest viewOptions = new RecipientViewRequest()
{
ReturnUrl = Utility.GetConfigValue("docSignReturnURL"),
ClientUserId = "1234", // must match clientUserId set in step #2!
AuthenticationMethod = "email",
UserName = recipientName,
Email = recipientEmail
};
// create the recipient view (aka signing URL)
ViewUrl recipientView = envelopesApi.CreateRecipientView(accountId, envelopeSummary.EnvelopeId, viewOptions);
// Start the embedded signing session!
//var value = System.Diagnostics.Process.Start(recipientView.Url);
SignedPDF signedPDF = new SignedPDF();
signedPDF.URL = recipientView.Url;
signedPDF.EnvelopeID = envelopeSummary.EnvelopeId;
return signedPDF;
}
catch (Exception ex)
{
throw new PDFSignException(ErrorConstants.THERE_WAS_AN_ERROR_WHILE_SIGNING_PDF);
}
finally
{
pdfStamper.Close();
pdfReader.Close();
}
}
Hi CodingDawg this is the JSON
{
"documents": [
{
"documentBase64": "",
"documentId": "1",
"name": "SignedFile.pdf"
}
],
"emailSubject": "Please sign this document",
"recipients": {
"signers": [
{
"clientUserId": "1234",
"email": "sagar.mali#tudip.com",
"name": "Sagar Mali",
"recipientId": "1",
"tabs": {
"signHereTabs": [
{
"documentId": "1",
"pageNumber": "1",
"recipientId": "1",
"xPosition": "192",
"yPosition": "679.968"
}
]
}
}
]
},
"status": "sent"
}
We have removed the base 64 string as the length was not supporting.
Make sure the signHere.XPosition & signHere.YPosition values are passed correctly.
The following statement could evaluate to a decimal value. Make sure it is an integer.
signHere.YPosition = (height - Convert.ToInt32(fieldPosition.position.Top + 25)).ToString();
Troubleshooting Step
Please run envelopeDefinition.ToJson() (Sdk documentation) and make sure the final Json posted to the DocuSign api is correct.

Resources