Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Webhook example #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions node+ts+express/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
BINANCE_SECRET_API_KEY=
BINANCE_API_KEY=
3 changes: 3 additions & 0 deletions node+ts+express/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/node_modules
.DS_Store
/dist
22 changes: 22 additions & 0 deletions node+ts+express/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "node",
"version": "1.0.0",
"description": "Example of binance signature uses using node + typescript + express",
"main": "dist/app.js",
"author": "Rubén Sahagún",
"license": "MIT",
"private": false,
"scripts": {
"build": "tsc",
"start": "npm run build && node dist/app.js"
},
"dependencies": {
"axios": "^1.2.0",
"crypto-js": "^4.1.1",
"express": "4.17.1",
"typescript": "4.9.3"
},
"devDependencies": {
"@types/express": "4.17.14"
}
}
10 changes: 10 additions & 0 deletions node+ts+express/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import express from "express";
import { loadWebHookEndpoints } from "./webhook";
const app = express();
const port = 3000;

loadWebHookEndpoints(app);

app.listen(port, () => {
return console.log(`Express is listening at http://localhost:${port}`);
});
100 changes: 100 additions & 0 deletions node+ts+express/src/webhook.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import axios from "axios";
import crypto from "crypto";
import hmac from "crypto-js/hmac-sha512";
import { Application } from "express";

const randomCharts = (length: number): string => {
let result = "";
const characters =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
};

const generateSignedPayload = (
payload: string
): { nonce: string; timestamp: number; signature: string } => {
const timestamp = Date.now();
const nonce = randomCharts(32);
const payload_to_sign = `${timestamp}\n${nonce}\n${payload}\n`;
const signature = hmac(
payload_to_sign,
process.env.BINANCE_SECRET_API_KEY || ""
)
.toString()
.toUpperCase();

return { nonce, timestamp, signature };
};

const verifyWebhookSignature = async (
binancePayTimestamp: string,
binancePayNonce: string,
bianacePaySignature: string,
data: any
): Promise<boolean> => {
console.log("Verifying Signature...");
const payload = `${binancePayTimestamp}\n${binancePayNonce}\n${JSON.stringify(
data
)}`;
const publicKey = await getPubKey();
console.log("PublicKey: ", publicKey);

const decodedSignature = Buffer.from(bianacePaySignature, "base64");

const verify = crypto.createVerify("SHA256");
verify.write(payload);
verify.end();

return await verify.verify(publicKey, decodedSignature);
};

const getPubKey = async (): Promise<string> => {
const { nonce, timestamp, signature } = generateSignedPayload(
JSON.stringify({})
);
const result = await axios.post(
"https://bpay.binanceapi.com/binancepay/openapi/certificates",
{},
{
headers: {
"BinancePay-Certificate-SN": process.env.BINANCE_API_KEY,
"Content-Type": "application/json;charset=utf-8",
"BinancePay-Timestamp": timestamp,
"BinancePay-Nonce": nonce,
"BinancePay-Signature": signature,
},
}
);

return result.data.data[0].certPublic;
};

export const loadWebHookEndpoints = (app: Application): void => {
app.post("/binance/order/notification", async (req, res) => {
const verified = await verifyWebhookSignature(
req.headers["binancepay-timestamp"] as string,
req.headers["binancepay-nonce"] as string,
req.headers["binancepay-signature"] as string,
req.body
);

console.log(
"********************BINANCE WEBHOOK CALL*******************",
req.body
);
if (verified) {
return res.status(200).send({
returnCode: "SUCCESS",
returnMessage: null,
});
} else {
return res
.status(401)
.send({ returnCode: "ERROR", returnMessage: "Not authorized" });
}
});
};
11 changes: 11 additions & 0 deletions node+ts+express/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist"
},
"lib": ["es2015"]
}
Loading