Balanced-Payments Try Catch response - try-catch

I've attempting to learn how to set up credit card payments and using a Balanced Payments test marketplace. I haven't ever set up a try catch statement before and I am having some trouble with processing the response.
Here is my controller try/catch statement:
try{
$card->debits->create(array(
"amount" => $amount,
"appears_on_statement_as" => "test",
"description" => $invoiceId,
"order" => $order,
));
} catch (Balanced\Errors\Declined $e) {
$this->arrResponse['status'] = $e->getMessage();
return Response::json($this->arrResponse);
}
$invoice->save();
// send email function...
//redirect
$this->arrResponse['status'] = SUCCESS;
return Response::json($this->arrResponse);
I can see the error on chrome developer tools, but I can't make it appear on my view.
Chrome dev tools 500 internal server error statement:
error: {type: "Balanced\Errors\Declined", message: "",…}
file: "/Applications/MAMP/htdocs/testcc/vendor/balanced/balanced/src/Balanced/Errors/Error.php"
line: 42
message: ""
type: "Balanced\Errors\Declined
processpayment.js file:
jQuery.post(baseURL+'/processPayment', {
uri: fundingInstrument.href,
amount: amount,
invoiceId: invoiceId,
}, function(r) {
// backend response
if (r.status === 200) {
$('#msgSection').empty().removeClass('alert-error alert-success').addClass('alert-success').text(' payment has been received').show();
} else {
// failure from backend
$('#msgSection').empty().removeClass('alert-success').addClass('alert-warning').text('error').show();
}
});
When test card is processed successfully, everything works and success message appears on my view. However, when I use a test card that is declined, no message is sent to my view. Anyone see what I am doing wrong?

try to check balanced-php client testsuite to see how they use try catch block from here
so your code would be like.
try{
$card->debits->create(array(
"amount" => $amount,
"appears_on_statement_as" => "test",
"description" => $invoiceId,
"order" => $order,
));
} catch (Balanced\Errors\Declined $e) {
$this->arrResponse['status'] = $e->category_code;
return Response::json($this->arrResponse);
}
$invoice->save();
// send email function...
//redirect
$this->arrResponse['status'] = SUCCESS;
return Response::json($this->arrResponse);
$e->category_code will be either funding-destination-declined or authorization-failed or card-declined

Related

WalletConnect :- Rainbow always show MATIC when transfer other coins by WalletConnect sendTransaction in react native

I am developing react native mobile application where user can transfer their amount by external wallet (Rainbow, MetaMask).
I am using 'polygon-rpc' network for my users.
The thing is working as expected but when execute transfer method by my contract by WalletConnect sendTransaction(txObj) library it navigate me to connected wallet and prompted the confirmation pop, where it show the my currency in MetaMask, but in Rainbow it always show Matic instead of POZ.
However it works well in Metamask and show the POZ, instead of MATIC.
I am using this code to procced transaction by WalletConnect external wallet
let toAddress = pozPouchFundWallet; // end address to transfer amount
let decimals = BigNumber(18);
let amount1 = new BigNumber(amountValue);
let value = amount1.times(new BigNumber(10).pow(decimals));
let contract = new Web3js.eth.Contract(App_ABI, POZ_TOKEN!);
try {
let dataa = await contract.methods
.transfer(toAddress, value.toString())
.encodeABI();
let txObj = {
// gas: Web3js.utils.toHex(100000),
data: Web3js.utils.toHex(dataa),
from: userWallet,
to: POZ_TOKEN, // Contractor token address
};
try {
const transactionHash = await connector
.sendTransaction(txObj)
.catch((_err: any) => {
Toast.show({
autoHide: true,
text1: t('topUpPoz.transactionFailed'),
type: 'error',
});
});
console.log('transactionHash is =', transactionHash);
resolve(transactionHash);
} catch (error) {
console.log('the connector error is = ', error);
reject(error);
}
} catch (err) {
console.log('contact error is = ', err);
reject(err);
}

Cannot update or save data on second or next user in mongodb

May I know what is the problem with my code for the backend. I try to create a place and update it in the user database. The problem is If I only have 1 user. The database can create and update the data but if I have more than 2 then, the data cannot be updated or created. Here is my code. I have been working on this part for so long, that I cannot find the solution.
const createFile = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
new HttpError('Invalid inputs passed, please check your data.', 422)
);
}
const { userId, Dataset } = req.body;
const createdFile = new File({
userId,
Dataset,
});
let user;
try {
user = await User.findById(userId);
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again 1',
500
);
return next(error);
}
if (!user) {
const error = new HttpError('Could not find user for provided id', 404);
return next(error);
}
try {
const sess = await mongoose.startSession();
sess.startTransaction();
await createdFile.save({ session: sess });
user.Dataset.push(createdFile);
await user.save({ session: sess });
await sess.commitTransaction();
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again.2',
500
);
return next(error);
}
res.status(201).json({ files: createdFile });
};
The error message that I got
Error: User validation failed: _id: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at ValidationError.inspect (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\error\validation.js:48:26)
at internal/per_context/primordials.js:23:32
at formatValue (internal/util/inspect.js:783:19)
at inspect (internal/util/inspect.js:337:10)
at formatWithOptionsInternal (internal/util/inspect.js:2016:40)
at formatWithOptions (internal/util/inspect.js:1898:10)
at console.value (internal/console/constructor.js:323:14)
at console.log (internal/console/constructor.js:358:61)
at createFile (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\controllers\files-controller.js:102:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
errors: {
_id: ValidatorError: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at validate (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1321:13)
at C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1297:24
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
properties: [Object],
kind: 'unique',
path: '_id',
value: new ObjectId("62c661c629d1cb99768efd05"),
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}
It already settle, I reroll the mongoose-unique-validator to 2.0.3 version
I use this command
npm install mongoose-unique-validator#2.0.3 --legacy-peer-deps
hope that someone with same issues as mine find my post and can help them to solve the same issues

CORS error while trying to access Flask API

I have a React front end and Flask Backend. There's a Long-Running Task in the Back end which is gonna start when I submit the Job from the Front end. I assigned 2 Buttons on the front end to Submit the Job and the Other One to Check the status of the Job and Retrieve Data if the Job Is Finished.
Front End Job Submit Function
const sendSubmitRequest = async () => {
try {
const resp = await axios.get('http://localhost:8000/submit-job/'+embedId);
if (resp.status === 202) {
setTaskId(resp.data.task_id)
console.log(resp.data);
alert("Job Submision Success..")
console.log("Job Submitted Successfully...")
} else {
alert("Job Submision Failed... \nCheck If the Video URL Is Correct")
}
} catch (err) {
// Handle Error Here
console.error(err);
}
};
Front End Check Job Status Function
const checkJobStatusTime = async () => {
let refreshId = null
try {
const refreshId = setInterval(async () => {
const resp = await axios.get('http://localhost:8000/get-result/'+taskId);
if (resp.status === 200 && resp.data.status === 'success') {
const resl = resp.data.result;
console.log(resl)
setData(resl);
alert("Data Retrieved Successfully...")
clearInterval(refreshId);
}
else if(resp.status === 200 && resp.data.status === 'not_found') {
clearInterval(refreshId);
} else {
console.log("Job Still Runing...")
}
}, 3000);
} catch(e) {
console.log(e);
clearInterval(refreshId);
}
}
In the Flask Back End, I have 2 Functions corresponds to the 2 Front End Functions
Backend Handle Job Submit Function
#app.route('/submit-job/<video_id>')
#cross_origin(origin='*', headers=['Content-Type', 'Authorization'])
def handle_submit(video_id):
job_id = id_generator()
executor.submit_stored(job_id, test_func, video_id)
return jsonify({'status': 'success', 'task_id': job_id, 'message': 'Job Submitted Successfully'}), 202
Backend Handle Check Job Status Function
#app.route('/get-result/<task_id>')
#cross_origin(origin='*', headers=['Content-Type', 'Authorization'])
def get_result(task_id):
if task_id in executor.futures._futures.keys():
if executor.futures.done(task_id):
future = executor.futures.pop(task_id)
return jsonify({'status': 'success',
'message': 'Job Completed Successfully',
'result': future.result()}), 200
else:
return jsonify({'status': executor.futures._state(task_id),
'message': 'Job Still Running',
'result': None}), 200
else:
return jsonify({'status': 'not_found',
'message': 'Task Id Cannot be Found.',
'result': None}), 200
Import 'cross_origin'
from flask_cors import cross_origin
PROBLEM:
When I Assigned the 2 Functions to the 2 Buttons Separately Everything works fine As Expected. However, If I try to call the Check status Function with the Job submit Function Like this,
const sendSubmitRequest = async () => {
try {
const resp = await axios.get(endPoint+'/youtube/submit-job/'+embedId);
if (resp.status === 202) {
setTaskId(resp.data.task_id);
console.log("Job Submitted Successfully...")
// Calling the Status Check Function
checkJobStatusTime();
} else {
alert("Job Submision Failed... \nCheck If the Video URL Is Correct")
}
} catch (err) {
// Handle Error Here
console.error(err);
}
};
This gives the CORs error.
Access to XMLHttpRequest at 'http://localhost:8000/get-result/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Can someone help me figure out why this is Happening?
Try to use the #cross_origin decorator without any arguments.
As it's written in the Documentation:
In the simplest case, simply use the default parameters to allow all origins in what is the most permissive configuration
Also headers is not a valid parameter for this decorator.
You might want to use allow_headers.

How to keep a count of number of requests when using mock service worker to test a React App?

In my app, the user enters their date of birth, a request is sent, and if it matches with the DOB in the database, they are sent to the next page. If it does not match, they are presented with the number of attempts they have left until their link is no longer valid. They have 3 attempts.
My question is, how would I mock this functionality using mock service worker? I would need to keep a count of the number of times this request has been attempted and failed.
Here is the code snippet of the handler, as you can see I have hardcoded the "1" after "Auth attempts" for now.
rest.post(
'https://myapiaddress/auth',
(req, res, ctx) => {
const enteredDateOfBirth = req.body.data.date_of_birth
let returnResult
if (enteredDateOfBirth === '1988-10-01') {
returnResult = res(
ctx.status(200),
ctx.json({
data: {
basic: 'fdafhaioubeaufbaubsaidbnf873hf8faoi'
}
})
)
} else {
returnResult = res(
ctx.status(400),
ctx.json({
errors: [
{ code: 89, message: 'Wrong date of birth. Auth attempts: 1' }
]
})
)
}
return returnResult
}
)
]
My jest test in which I confirm the incorrect date 3 times:
// 1st attempt
userEvent.click(confirmBtn)
const warningAttemptsNum1 = await screen.findByText('1/3 attempts')
const dateEntered = screen.getByText('(12/10/2010)')
expect(warningAttemptsNum1).toBeInTheDocument()
expect(dateEntered).toBeInTheDocument()
// 2nd attempt
userEvent.click(confirmBtn)
const warningAttemptsNum2 = await screen.findByText('2/3 attempts')
expect(warningAttemptsNum2).toBeInTheDocument()
userEvent.click(confirmBtn)
// Entering 3 times shows "link no longer valid" screen
userEvent.click(confirmBtn)
const linkNoLongerValidText = await screen.findByText(
'This link is no longer valid'
)
expect(linkNoLongerValidText).toBeInTheDocument()
Your general idea is correct: you can keep a track of the count of requests made by incrementing a number in the response resolver.
Here's how I'd recommend doing it:
function withTimes(handler) {
let attempts = 0
return (req, res, ctx) => {
attempts++
handler(req, res, ctx, attempts)
}
}
rest.post('/endpoint', withTimes((req, res, ctx, attempts) => {
const MAX_ATTEMPTS = 3
const dob = req.body.data.date_of_birth
if (dob === '1988-10-01') {
return res(ctx.json({ data: { basic: 'abc-123' }}))
}
return res(
ctx.status(400),
ctx.json({
errors: [
{
code: 89,
message: `Wrong date of birth. Attempts left: ${MAX_ATTEMPTS - attempts}`
}
]
})
)
}))
I also see that the response body structure you use is very similar to such of GraphQL. Note that you should use the GraphQL API to handle GraphQL operations.

Node.js SQL server crashes when receiving multiple requests

I have a NodeJS application which is my server and I created a Database class to help me handle querying my SQL DB. If I send requests a second between each other, everything runs fine.. no problems.. But if I start spamming requests to my server it crashes due to Error: Cannot enqueue Quit after invoking quit.
Here's my query function inside my Database class
static query(query: string): Promise<any> {
console.log('Query: ' + query);
return new Promise((resolve, reject) => {
this.connect().then(success => {
sqlConn.query(query, (err, results) => {
if (err) { return reject(err);
} else {
return resolve(results);
}
});
}).catch(err => {
return reject(err);
}).then( () => {
if (sqlConn.state !== 'disconnected') {
sqlConn.end();
}
});
});
};
and here's the this.connect() function
static connect(): Promise<any> {
return new Promise((resolve, reject) => {
sqlConn = mysql.createConnection(this.connectionData);
sqlConn.connect(err => {
if (err) { return reject(err); } else {
return resolve('SQL connection established');
}
});
});
};
I'm pretty sure the problem appears sometimes, it would still be
processing one query, and then another query comes before the first
one finishes, so it would call sqlConn.end() twice, even when it's
already disconnected? Any help is greatly appreciated...
> Main goal is for the query to wait till it's 100% done before it runs
the next one..
You can simplify your code by using the npm module mysql and use it's built-in connection pool.
From the documentation:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'example.org',
user : 'bob',
password : 'secret',
database : 'my_db'
});
pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
You can, of course, create your own function that promisifies that call like this:
function query (sql) {
return new Promise((resolve, reject) => {
pool.query(sql, (error, results, fields) =>
error ? reject(error) : resolve({ results, fields });
};
}
If you really wants to use this approach then please use eachSeries function of async library.
var chunkedArray= [];
async.eachSeries(chunkedArray, startUpload, endUpload);
funtion startUpload(data,cb){
//iterate over every single item in array 1 at a time
}
function endUplaod(err){
//finally call this
}
This might help:-
https://caolan.github.io/async/docs.html#eachSeries
But i rather suggest you to use pooling of connection which make less overhead on your db and you can use your mysql more efficiently then making multiple connection.
// Load module
var mysql = require('mysql');
// Initialize pool
var pool = mysql.createPool({
connectionLimit : 10,
host : '127.0.0.1',
user : 'root',
password : 'root',
database : 'db_name',
debug : false
});
module.exports = pool;

Resources