mcaptcha-api-js/src/index.js

45 lines
1.2 KiB
JavaScript

/**
* mCaptcha API client
*/
class MCaptcha {
/**
* @constructor
* @param {string} sitekey - the unique identifier of captcha configuration
* @param {string} secret - account secret, can be obtained from mCaptcha dashboard
* @param {URL} instanceUrl - the URL of the mCaptcha instance you are using
*/
constructor(sitekey, secret, instanceUrl) {
this.sitekey = sitekey;
this.secret = secret;
this.verify_url = new URL(instanceUrl);
this.verify_url.pathname = "/api/v1/pow/siteverify";
}
/**
* Verify authorization token presented by user
* @param {string} token
*/
async verify(token) {
let payload = {
token: token,
secret: this.secret,
key: this.sitekey,
};
let res = await fetch(this.verify_url, {
method: "POST",
body: JSON.stringify(payload),
headers: { "Content-Type": "application/json; charset=UTF-8" },
});
if (res.status != 200) {
let error = await res.json();
error = `status code: ${res.status}: ${error.error}`;
throw new Error(error);
}
res = await res.json();
console.log(res);
return res.valid;
}
}
module.exports = MCaptcha;