Mercado Pago Client onPaymentMethodsRecieved - mercadopago

I am trying to integrate Mercado Pago to my React aplication, first I want to connect the client so I can set up some alerts (/process-payments is going to be done through python)
I am having a problem. I can not log PaymentMethods nor Issuers. Strangely my issuers field is populated. For example whenever I put a random card Number I get logged the installments yet not the issuers (although I can see them)
Console and Product image
The following is my code:
useEffect(() => {
if (MercadoPago) {
const mp = new MercadoPago(
PUBLIC_KEY
);
console.log("mp es", mp);
const cardForm = mp.cardForm({
amount: "200",
autoMount: true,
form: formConfig,
callbacks: {
onFormMounted: (error) => {
if (error) {
return console.warn("Form mounted handling error: ", error);
}
console.log("Form Mounted");
},
onPaymentMethodsRecieved: (error, paymentMethods) => {
console.log("In Payment methods");
if (error) {
window.alert("No payment methods");
}
console.log("Payment Methods Available", paymentMethods);
},
onIssuersRecieved: (error, issuers) => {
if (error) return console.warn("issuers handling error: ", error);
console.log("Issuers available: ", issuers);
},
onInstallmentsReceived: (error, installments) => {
if (error)
return console.warn("installments handling error: ", error);
console.log("Installments available: ", installments);
},
onCardTokenRecieved: (error, token) => {
if (error) {
return console.warn("Token no se pudo crear: ", error);
}
console.log("Token available: ", token);
},.......}

I think you misspelled 'onPaymentMethodsRecieved', it should be onPaymentMethodsReceived. The same happens in the others logs.

Related

"[Function: Error Ctor]" error in console

the first console log is getting logged but the second one isn't
and the catch is catching an error which I do not understand ...
this is my route:
router.post("/buy", JwtAuthenticateToken, async (req, res, next) => {
try {
const entry = new PositionModel(req.body)
console.log("new", entry)
const result = await entry.save()
console.log("saved", result)
} catch (error) {
console.log(error)
next(error)
}
})
this is what gets printed in the console:
new {
_id: 6125514a26fb7d06603b1a5a,
stock: 'Apple Inc',
ticker: 'AAPL',
purchasePrice: 149.62,
shares: 1,
owner: 6124e2a70d195a05f4e480cd
}
[Function: ErrorCtor]
I was passing an error to an error creator in my .post("validate")
probably the dumbest 5 lines of code I have ever written.
post("validate", (error, doc, next) => {
if (error) {
const err = createError(400, error)
next(err)
} else {
next(error)
}
})

Tez Payment Request API

I'm trying to integrate Google-Tez payment in my site, But When I'm calling request.show() getting error msg as
"Payee isn't a valid merchant"
, When i call checkCanMakePayment() getting error msg as
"Cannot query payment request"
and I enclose my code below. My UPI ID is "hsbc". Can anyone help me to troubleshoot this issue? and I need to know is there any process like merchant has to register with Google Tez
function onBuyClicked() {
const creditCardPaymentMethod = {
supportedMethods: 'basic-card',
data: {
supportedNetworks: ['visa', 'mastercard'],
supportedTypes: ['credit', 'debit']
}
};
const supportedInstruments = [
{
supportedMethods: ['https://tez.google.com/pay'],
//supportedMethods:[creditCardPaymentMethod],
data: {
pa:'**********',
pn:'**********',
tr:'123456ABCDEFSD',
url:'***********',
mc:'*********',
tn:'Purchase in Merchant'
}
}
];
var details =
{
total:
{
label:'Total',
amount: {
currency:'INR',
value:'10.01' //sample amount
}
},
displayItems: [
{
label:'Original Amount',
amount: {
currency:'INR',
value:'10.01'
}
}
]
};
var request =null;
try {
request = new PaymentRequest(supportedInstruments, details);
console.log(request);
/*request.show()
.then(function(result){
alert("hai");
})
.catch(function(err){
alert('Payment Request Error: '+ err.message+' 74');
});*/
}catch (e) {
alert('Payment Request Error: '+ e.message+'77');
console.log('Payment Request Error: '+ e.message);
//return;
}
if (!request) {
alert('Web payments are not supported in this browser 77');
console.log('Web payments are not supported in this browser.');
// return;
} 
var canMakePaymentPromise = checkCanMakePayment(request);
canMakePaymentPromise
.then(function(result){
showPaymentUI(request,result)
})
.catch(function(err){
console.log('Error in calling checkCanMakePayment: ' + err);
});
}
const canMakePaymentCache = 'canMakePaymentCache';
function checkCanMakePayment(request){
// Checks canMakePayment cache, and use the cache result if it exists.
if(sessionStorage.hasOwnProperty(canMakePaymentCache)){
return Promise.resolve(JSON.parse(sessionStorage[canMakePaymentCache]));
}
// If canMakePayment() isn't available, default to assuming that the method is supported
var canMakePaymentPromise = request.canMakePayment();
if(request.canMakePayment){
canMakePaymentPromise = request.canMakePayment();
}
return canMakePaymentPromise
.then(function(result){
sessionStorage[canMakePaymentCache] = result;
return result;
})
.catch(function (err){
alert('Error calling canMakePayment: '+ err);
console.log('Error calling canMakePayment: '+ err);
});
}
function showPaymentUI(request, canMakePayment){
if(!canMakePayment){
handleNotReadyToPay();
return;
}
// Set payment timeout.
var paymentTimeout = window.setTimeout(function(){
window.clearTimeout(paymentTimeout);
request.abort()
.then(function(){
alert('Payment timed out after 20 mins 129');
console.log('Payment timed out after 20 mins');
}).catch(function(){
alert('Unable to abort,user is in process of paying 132');
console.log('Unable to abort,user is in process of paying');
});
}, 20 * 60 * 1000);
request.show()
.then(function(paymentResponse){
window.clearTimeout(paymentTimeout);
alert("Request Success");
console.log(paymentResponse);
processResponse(paymentResponse); // Handle response from browser
})
.catch(function (err){
alert(err +'142');
console.log(err);
});
}
function handleNotReadyToPay(){
alert("Tez is not ready to handle 149");
}
function processResponse(paymentResponse){
var paymentResponseString = paymentResponseToJsonString(paymentResponse);
console.log(paymentResponseString);
/* fetch('/buy',{
method: 'POST',
headers: new Headers({'Content-Type':'application/json'}),
body:paymentResponseString
})
.then(function(buyResult){
console.log('Buy Result'+buyResult);
})
.catch(function(err){
console.log('Unable to process payment. '+err);
});*/
}
onBuyClicked();
"Payee isn't a valid merchant" error comes when you use customer VPA in place of merchant VPA in the 'pa' field.
Resolution:
Use VPA which is issued for the merchant.

Office JS - Add customProperty to new document

I´m developing an addIn for office (word) and I´m stuck with this problem. I need to assign custom properties to a new document that is going to be opened in a new window/instance.
I´m already using custom properties for documents that are already opened this way:
setProperty(propName, propValue) {
Word.run(context => {
context.document.properties.customProperties.add(propName, propValue);
return context.sync();
}).catch(error => {
if (error instanceof OfficeExtension.Error) {
console.log(
"Error code and message: " + JSON.stringify(error.debugInfo)
);
}
});
}
getFileOverride(attach, file) {
self.getDocumentAsBase64(attach.id).then(data => {
Word.run(context => {
let body = context.document.body;
body.insertFileFromBase64(data, Word.InsertLocation.replace);
return context
.sync()
.then(() => {
self.setProperty("fileId", file.id);
self.setProperty("attachId", attach.id);
})
.then(context.sync)
.catch(error => {
self.updateStatus("Error al obtener el archivo");
if (error instanceof OfficeExtension.Error) {
console.log(
"Error code and message: " + JSON.stringify(error.debugInfo)
);
}
});
}).catch(error => {
if (error instanceof OfficeExtension.Error) {
console.log(
"Error code and message: " + JSON.stringify(error.debugInfo)
);
}
});
});
}
But when I create a new document I don´t know how to achieve this. I´ve tried the following but gives a General Exception error:
getDocumentAsBase64(function(data) {
Word.run(function(context) {
var myNewDoc = context.application.createDocument(data);
context.load(myNewDoc);
return context
.sync()
.then(function() {
myNewDoc.properties.load();
myNewDoc.properties.customProperties.add("custom", "prop");
myNewDoc.open();
})
.then(context.sync)
.catch(function(myError) {
//otherwise we handle the exception here!
updateStatus(myError.message);
});
}).catch(function(myError) {
updateStatus(myError.message);
});
});
I've tried making a function similar to setProperty but it doesn't add the properties:
function setExternalProperty(document, propName, propValue) {
Word.run(context => {
document.properties.load();
document.properties.customProperties.add("custom", "prop");
return context.sync();
}).catch(error => {
if (error instanceof OfficeExtension.Error) {
console.log("Error code and message: " + JSON.stringify(error.debugInfo));
}
});
}
How can I achieve this?
I found the solution, it was quite simple. I change my function to this:
getFileNew(attach, file) {
self.getDocumentAsBase64(attach.id).then(data => {
Word.run(context => {
var myNewDoc = context.application.createDocument(data);
myNewDoc.properties.load();
myNewDoc.properties.customProperties.add("fileId", file.id);
myNewDoc.properties.customProperties.add("fileName", file.name);
myNewDoc.properties.customProperties.add("attachId", attach.id);
myNewDoc.properties.customProperties.add("attachName", attach.name);
myNewDoc.open();
return context.sync()
}).catch(error => {
if (error instanceof OfficeExtension.Error) {
console.log(
"Error code and message: " + JSON.stringify(error.debugInfo)
);
}
});
});
}
SIDENOTE: This only works on desktop version. If you want to open a document in a new window in Office Online you have to omit the customProperties or it´ll throw an exception

React-native Log in with Facebook App refreshes app

I am using react-native-fbsdk and am on IOS. When users log in with Facebook their are two buttons they can press. Log in with the Facebook App or Log in with Phone Number or Email Address. Logging in with the Phone Number or email address works perfectly, I get the user object and create a user account for them. But when users press Log in with the Facebook App I don't get sent a user object, and the whole app refreshes where they get pushed to the log in page and the Facebook button has turned to Log out. I am not too sure on how to approach this as when users log in with the Facebook App none of my console.logs or alerts are getting called and the whole app just refreshes. Any help would be very much appreciated.
<LoginButton
readPermissions={["email","public_profile"]}
onLoginFinished={
(error, result) => {
console.log("onLoginFinished: ", result);
if (error) {
console.log("login has error: ", result.error);
} else if (result.isCancelled) {
console.log("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
console.log("accessToken.toString(): ", accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log('Error fetching data: ', error)
//lert('Error fetching data: ' + error.toString());
} else {
console.log("responseInfoCallback:", result)
this.state.fbobj = result;
this.sendAjax();
//alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'email,name'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => console.log("Logout")}
In your button action, you will need something like this:
import { LoginManager, AccessToken } from 'react-native-fbsdk'
handlePressFacebookLogin = () => {
LoginManager.logInWithReadPermissions(['public_profile', 'email']).then(
(result) => {
if (!result.isCancelled) {
AccessToken.getCurrentAccessToken().then((data) => {
console.log(data)
})
}
}
)
}

Multiple functions in restify function to elasticsearch client

I'm building a REST API using node and restify that communicaties with an elasticsearch database. Now when I delete an object, I want this to do a kind of cascading delete to some other objects. I know this is not really what to use elasticsearch for but bear with me.
So here is my code:
function deleteHostname(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
var endpoints = [];
client.search({
index: 'test',
type: 'something',
body: {
from: 0, size: 100,
query: {
match: {
hostname: 'www.test.com'
}
}
}
}).then(function (error, resp) {
if(error) {
res.send(error);
}
endpoints = resp.hits.hits;
for (index = 0, len = endpoints.length; index < len; ++index) {
client.delete({
index: 'test',
type: 'something',
id: endpoints[index]._id
}, function (error, response) {
if(error) {
res.send(error);
}
});
}
res.send(endpoints);
return next();
});
}
So basically I just want to search for any objects with hostname www.test.com ( I just hard coded this to test it ). Then I want to delete all objects I found. It follows the error path and sends me this:
{
"took":1,
"timed_out":false,
"_shards":{
"total":5,
"successful":5,
"failed":0
},
"hits":{
"total":1,
"max_score":2.098612,
"hits":[
{
"_index":"test",
"_type":"something",
"_id":"123456",
"_score":2.098612,
"_source":{
"duration":107182,
"date":"2016-05-04 00:54:43",
"isExceptional":true,
"hostname":"www.test.com",
"eta":613,
"hasWarnings":false,
"grade":"A+",
"ipAddress":"ipip",
"progress":100,
"delegation":2,
"statusMessage":"Ready"
}
}
]
}
}
So in my opinion this doesn't look like an error? So why am I getting it back as an error? If I remove:
if(error) {
res.send(error);
}
From my code, I won't get any response.
You need to change your code like this (see the changes denoted by -> to the left):
if(error) {
1-> return res.send(error);
}
endpoints = resp.hits.hits;
for (index = 0, len = endpoints.length; index < len; ++index) {
2-> (function(id){
client.delete({
index: 'test',
type: 'something',
3-> id: id
}, function (error, response) {
if(error) {
4-> next(error);
}
});
5-> })(endpoints[index._id]);
}
6-> //res.send(endpoints);
I'm now explaining each change:
If you don't return you'll send the error and then you'll continue with processing the hits
(3/5) Since client.delete is an asynchronous function, you need to call it in an anonymous function
In case of error you need to call next(error) not res.send
You cannot send the response at this point since your for loop might not be terminated yet. Instead of a for loop, you should use the excellent async library instead (see an example of using asynch.each below)
Async example:
var async = require('async');
...
if(error) {
return res.send(error);
}
endpoints = resp.hits.hits;
async.each(endpoints,
function(endpoint, callback) {
client.delete({
index: 'test',
type: 'something',
id: endpoint._id
}, callback);
},
// this is called when all deletes are done
function(err){
if (err) {
next(err);
} else {
res.send(endpoints);
next();
}
}
);
Another solution for you to achieve exactly what you want is to use the delete by query plugin. That feature allows you to do all the above in a single query.
If you are still on ES 1.x, delete-by-query is still part of the core and you can simply call the deleteByQuery function of the Javascript client.
If you are on ES 2.x, delete-by-query is now a plugin, so yo need to install it and then also require the deleteByQuery extension library for the Javascript client
function deleteHostname(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
client.deleteByQuery({
index: 'test',
type: 'something',
body: {
query: {
match: { hostname: 'www.test.com' }
}
}
}, function (error, response) {
if (error) {
next(error);
} else {
res.send(endpoints);
next();
}
});
}