Stellar Node JS Payment Error - node.js

I'm working on a simple API, we are using this SDK but when we try on live with this script.
var StellarSdk = require('stellar-sdk');
StellarSdk.Network.usePublicNetwork();
var keypair = StellarSdk.Keypair.fromSecret('OUR SECRET');
var server = new StellarSdk.Server('https://horizon.stellar.org');
var sourceKeypair = StellarSdk.Keypair.random();
console.log(sourceKeypair.publicKey());
console.log(sourceKeypair.secret());
var secret = sourceKeypair.secret();
var public = sourceKeypair.publicKey();
server.loadAccount(keypair.publicKey())
.then(function(source) {
var transaction = new StellarSdk.TransactionBuilder(source)
.addOperation(StellarSdk.Operation.payment({
destination: public,
amount: "1",
asset: StellarSdk.Asset.native()
}))
.build();
transaction.sign(keypair);
return server.submitTransaction(transaction);
})
.then(function() {
return server.loadAccount(public)
})
.catch(function(error) {
console.error('Error!', error);
});
On the script we created a new account and we want to activate it with 1 lumen, the secret of the Payment have at least 1000 lumens, but when we make the transactions, it give this error:
Error! { [BadResponseError: Transaction submission failed. Server responded: 400 Bad Request]
name: 'BadResponseError',
message: 'Transaction submission failed. Server responded: 400 Bad Request',
data:
{ type: 'https://stellar.org/horizon-errors/transaction_failed',
title: 'Transaction Failed',
status: 400,
detail: 'The transaction failed when submitted to the stellar network. The `extras.result_codes` field on this response contains further details. Descriptions of each code can be found at: https://www.stellar.org/developers/learn/concepts/list-of-operations.html',
instance: 'horizon-001a/Fm1q5QnVH4-247091670',
extras:
{ envelope_xdr: 'AAAAACO0e3CpDcv7A+FzZkIdKI0Jqhln3kEwK3OsVJW6fOYMAAAAZADzojYAAAAaAAAAAAAAAAAAAAABAAAAAAAAAAEAAAAA90HkP1W5wCsFRAGGKE1z1b+b7PnetRAQI6/XIo9R2PwAAAAAAAAAAACYloAAAAAAAAAAAbp85gwAAABAr1tWwYjH5fjEUL6gsgFCrJbQakDuSk6bE2AYE51NAZkH4N6f7JCkwAEH2A1XSG334sprokpxy7lWcVPW92XgBw==',
result_codes: [Object],
result_xdr: 'AAAAAAAAAGT/////AAAAAQAAAAAAAAAB////+wAAAAA=' } } }
Any advice?

Related

Node.js POST Request through Angular application returns Error 404 “not found"

I am making an API using Node.js that connects to an SQL Server database. My GET requests work well, but my POST request gives me errors. I have divided my node project into two files, a routes file and a controllers file.
The code in my routes file is as follows:
module.exports = (app) => {
const UsrContrllr = require('../Controllers/users.controllers');
//1. GET ALL USERS
app.get('/api/users', UsrContrllr.getAllUsers);
//2. POST NEW USER
app.post('/api/user/new', UsrContrllr.addNewUser);
};
And the code in my controllers file is given below:
const mssql = require('mssql');
exports.getAllUsers = (req, res) =>
{
// Validate request
console.log(`Fetching RESPONSE`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `SELECT * FROM USERS`;
request.query(queryStr, function (err, recordset) {
if (err) console.log(err)
else {
if (recordset.recordset.toString() === '') {
res.send('Oops!!! Required data not found...');
}
else {
// send records as a response
res.send(recordset);
}
};
});
};
exports.addNewUser = (req, res) =>
{
// Validate request
console.log(`INSERTING RECORD ${req.body}`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `INSERT INTO USERS (USERCODE, PASSWORD, LANGUAGE, USERCLASS, FIRSTNAME, LASTNAME, CONTACTNO) VALUES ('${req.body.usercode}', '${req.body.password}', 'EN', '0', '${req.body.firstname}', '${req.body.lastname}', '${req.body.contactno}');`;
console.log(queryStr);
request.query(queryStr, function (err, recordset) {
if (err) console.log(err)
else {
if (recordset.recordset.toString() == '') {
res.send('Oops!!! Required data not found...');
}
else {
// Send records as response
res.send(recordset);
}
};
});
};
When I run the POST request from my angular application, I get an HttpErrorResponse, Error 404 not found.
error: “Error: Cannot POST /api/users/new"
message: "Http failure response for http://url:port/api/users/new: 404 Not Found"
name: "HttpErrorResponse"
ok: false
status: 404
statusText: "Not Found”
url: "http://url:port/api/users/new”
The angular code in the service file is as follows:
private url = 'http://url:port/api/users';
signup(fName: string, lName: string, usrCode: string, pwd: string, cntctNbr: string) {
const headers = new HttpHeaders().set('Content-Type', 'application/json');
const newUsr = {
usercode: usrCode,
password: pwd,
firstname: fName,
lastname: lName,
contactno: cntctNbr
}
this.http.post(this.url + '/new', JSON.stringify(newUsr), { headers: headers }).subscribe(data => {
console.log(data);
});
}
I don’t understand why I am unable to add in new users. I’ve been told my code appears fine, but I don’t see any results. Where am I going wrong?
You are receiving a 404 (Not found) error because your POST route is defined as /user/new but in your angular app you are calling http://url:port/api/users/new
Correct the code to the following in your API:
app.post('/api/users/new', UsrContrllr.addNewUser);

Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM

I got this code from my client iOS app on XCode console
Firebase registration token: diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h
diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h
NodeJS
console.log("START");
var FCM = require('fcm-node');
var serverKey = require('/Users/bheng/Desktop/Apps/APNS/node/mhn-app-firebase-adminsdk-bs45c-5ac3770488.json')
var fcm = new FCM(serverKey)
var collapseKey = 'new_message';
var message = {
to: 'diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
data: {
cpeMac: '000000000000',
type: 'malware'
},
notification: {
title: 'Hello baby',
body: 'Nice body',
tag: collapseKey,
icon: 'ic_notification',
color: '#18d821',
sound: 'default',
},
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!")
console.log(JSON.stringify(err));
} else {
console.log("Successfully sent with response: ", JSON.stringify(response))
}
})
console.log("END");
Result
When I run it
node app.js
I kept getting
START
END
Successfully sent with response: {"results":[{"error":{"code":"messaging/invalid-registration-token","message":"Invalid registration token provided. Make sure it matches the registration token the client app receives from registering with FCM."}}],"canonicalRegistrationTokenCount":0,"failureCount":1,"successCount":0,"multicastId":7577724855311354000}
How would one go about debugging this further?
your token has some additional random string such as
to: 'diWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
just remove : diWY78iar8s: from your token string
console.log("START");
var FCM = require('fcm-node');
var serverKey = require('/Users/bheng/Desktop/Apps/APNS/node/mhn-app-firebase-adminsdk-bs45c-5ac3770488.json')
var fcm = new FCM(serverKey)
var collapseKey = 'new_message';
var message = {
to: 'APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7hdiWY78iar8s:APA91bHJAzXe384OEYvfk4bKsyS1NQvteph7DwG7JRIMm_HuXg8EeNllVrsSi0v9W_Gh95ezbOStp3ZWuWl0AzFKxMaCOjN81yiz7A5qhkONrd7lP2CTkUbFErw28r3ONTLvo8c8sO7h',
data: {
cpeMac: '000000000000',
type: 'malware'
},
notification: {
title: 'Hello baby',
body: 'Nice body',
tag: collapseKey,
icon: 'ic_notification',
color: '#18d821',
sound: 'default',
},
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!")
console.log(JSON.stringify(err));
} else {
console.log("Successfully sent with response: ", JSON.stringify(response))
}
})
console.log("END");
Response from FCM :
Successfully sent with response: { results: [ { messageId: '0:1543448946734425%479ec0e2479ec0e2' } ],
canonicalRegistrationTokenCount: 0,
failureCount: 0,
successCount: 1,
multicastId: 6133765431734591000 }
One of the interesting reasons for invalid registration is: that device have a different token. Maybe you are trying to use a past token.
In my case what happened was I was getting the FCMRegistrationToken from my colleague via Discord and the Ctrl+C Ctrl+V was modifying the token. On obtaining the token via email solved the issue.

Lambda function timing out after 10 seconds

Code:
const knex = require('knex')({
client: 'mysql',
connection: {
host: process.env.database_host,
user: process.env.database_user,
password: process.env.database_pass,
database: process.env.database_db,
charset: 'utf8'
}
});
const bcrypt = require('bcrypt');
const bookshelf = require('bookshelf')(knex);
const User = bookshelf.Model.extend({
tableName: 'users'
});
const checkValues = (values) => {
// todo: add data validation
return true;
};
exports.test = (database) => {
// todo: add tests
};
exports.handler = (event, context, callback) => {
let salt = bcrypt.genSaltSync();
let values = {
first_name: event.firstname,
last_name: event.lastname,
username: event.username,
date_of_birth: event.birthday,
password: bcrypt.hashSync(event.password, salt),
password_salt: salt
};
if (!checkValues(values)) {
callback(null, {
success: false,
error: {
id: 2,
details: 'data validation error'
}
});
context.done(null, "User not created");
return;
}
try {
new User({
'first_name': values.first_name,
'last_name': values.last_name,
'username': values.username,
'date_of_birth': values.date_of_birth,
'password': values.password,
'password_salt': values.password_salt
}).save();
callback(null, {
success: true
});
context.done(null, "User created");
} catch (err) {
console.log(err);
callback(null, {
success: false,
error: {
id: 1,
details: 'error inserting user into database'
}
});
context.done(null, "User not created");
}
};
I am trying to make a basic sign up api endpoint using AWS API Gateway and Lambda functions, however every time I post the information to the api gateway I get the error
{
"errorMessage": "2017-09-07T08:38:50.174Z f2368466-93a7-11e7-b4bc-01142a109ede Task timed out after 10.00 seconds"
}
I have tried using different database libraries but I seem to always be hitting the same problem. The database connection works I know this because the user does infact get added to the users table in the database and the password is successfully hashed..
I have also tried using asynchronous bcrypt but it doesn't make any difference to the result, it still does it but says it times out.
Lambda doesn't seem to be terminating properly, something keeps the process still running and I can't figure out what, any ideas?
i had the similar issue using API gateway invoking my lambda.
The default timeout for API gateway is 30 seconds. If your response is not ready within in 30 seconds, you will be timed out though your lambda would still run!
So may be try to get the response back within 30 seconds. If not have one lambda being invoked from the API and give the response back immediately and let the first lambda invoke your second lambda and that will run upto max time which is 5 mins.
Thanks

Getting error while making charges on connected Standalone Acount(Stripe)

I'm trying to make charges on connected standalone acount. I'm using parse cloud code for that...it gives me following error:
Error Domain=Parse Code=141 "ReferenceError: stripe is not defined
Below is my code..
var Stripe = require('stripe');
Stripe.initialize('**************************');
Parse.Cloud.define("hello", function(request, response) {
var token = request.params.stripeToken;
var userid = request.params.userId;
stripe.charges.create(
{
amount: 1000,
currency: "usd",
source: token,
description: "Example charge",
application_fee: 123
},
{stripe_account: userid},{
success: function(httpResponse) {
response.success("Purchase made!");
},
error: function(httpResponse) {
response.error(error);
}
});
});

braintree + NodeJS gives an "authentication Error "

I'm trying to build a payment gateway library using braintree's NodeJS library, I'm making an ajax call from front end with the card data.
Client-Side
var card_data = {
type: "AmEx",
number: "3XXXXXXXXXXXXXX",
expire_month: "XX",
expire_year: "201X",
cvv2: "XXX",
name: "sandeep",
price : "200",
currency : "USD"
};
Ajax call,
$.ajax({
method: "GET",
url: "http://localhost:3000/paymentPath_braintree",
data: card_data
}).done(function(message){
console.log(message);
}).fail(function(data, message){
console.log(message);
});
Server-Side
var braintreePay = require('braintree');
app.get("/payment_braintree", function(request, response){
var data = request.query;
var gateway = braintreePay.connect({
environment: braintreePay.Environment.Sandbox,
merchantId: "MymerchentID",
publicKey: "MypublicKey",
privateKey: "MyprivateKey",
});
var saleRequest = {
amount: data.price,
creditCard: {
number: data.number,
cvv: data.cvv2,
expirationMonth: data.expire_month,
expirationYear: data.expire_year.slice(2),
cardHolder: data.name
},
options: {
submitForSettlement: true
}
};
gateway.transaction.sale(saleRequest, function(error, result){
if(error){
console.log(error.name);
throw error;
}
if(result.success){
response.send(result.transaction.id);
} else {
response.send(result.message);
}
});
});
I have cross checked everything, from keys and card data everything is in order but i am getting an error in callback after making gateway.transaction.sale(...); called Authentication Error . Which i tried to figure out for hours but could not get through.
error object is
authenticationError: Authentication Error
arguments: undefined
message: "Authentication Error"
name: "authenticationError"
stack: undefined
type: "authenticationError"
Where am i going wrong?
I have created an account sandbox.braintreegateway those key credentials are from the account that i have created, i din't create an app like how its done in paypal.
I am going through lack of understanding in Braintree integration.
Are their any proper documented resource.

Resources