How to call a function upon http get or post? - angularjs

I'm sure this is a stupid question but I am very new to the backend so please forgive me.
I am building an angularjs app with express/node also and am trying to integrate PayPal (as a Node.js SDK), what I want is to call the pay method on the SDK from an angular controller and I am doing as follows:
On button click:
// controller
$scope.pay = function(amount) {
PaymentFactory.doPayment(amount);
}
Payment Factory:
// PaymentFactory
return {
doPayment: function(amount) {
$http.get("../../../server/payments/paypal.js")
.then(function(response) {
console.log( response );
})
}
}
Then the server-side file is as below:
require('paypal-adaptive');
var app = require('../../server.js');
var PayPal = require('paypal-adaptive');
var paypalSdk = new PayPal({
userId: 'userid',
password: 'password',
signature: 'signature',
sandbox: true //defaults to false
});
var payload = {
requestEnvelope: {
errorLanguage: 'en_US'
},
actionType: 'PAY_PRIMARY',
currencyCode: 'GBP',
feesPayer: 'EACHRECEIVER',
memo: 'Chained payment example',
cancelUrl: 'returnUrl,
returnUrl: 'cancelUrl',
receiverList: {
receiver: [
{
email: 'email1',
amount: '3.40',
primary:'true'
},
{
email: 'email2',
amount: '1.20',
primary:'false'
}
]
}
};
paypalSdk.pay(payload, function (err, response) {
if (err) {
console.log(err);
} else {
// Response will have the original Paypal API response
// But also a paymentApprovalUrl, so you can redirect the sender to checkout easily
console.log('Redirect to %s', response.paymentApprovalUrl);
return response;
}
});
Of course the get request just returns a string of the server-side file contents, I understand why the above doesn't work but not sure how one would make it work. My aim is to call the PayPal SDK from the angular factory and get back the response so that I can redirect a user to a URL. A direct solution would be helpful but even more so I need pointers to the principles that I am not understanding here as far as how one should call functions upon user actions to get this data from the server side. I have tried searching but I don't really the language to use in my search.

All you need to do is use curl (node-curl npm module). Using curl will help you post data to your paypal url and get back the response. Now you need to handle this response from paypal and accordingly generate your own response to be received by the angular http method.

Related

Cypress stubbing XHR response based on request

I am beginer in Cypress and looking for help with network stubbing.
My UI tiggers 3 API calls concurrently upon clicking on a button in the UI. All 3 API are of same endpoint, BUT each of them have different request and response.
I am able to stub the json response using cy.fixture, cy.server() and cy.route().
My need is to 'only stub the 3rd XHR call response', but, my test stubs all three because of the same endpoint.
Any suggessions on how could I test it using any condition ? example - Only stub the call if the parameters of 'request'XHR is 'XXX'?
I tried using before and after the .click() of submit button but that didn't work.
cy.fixture('myfixture').then(jsonresponse => {
function FixtureController(request, response) {
if (cy.url().request.body.contains("XXX")) {
cy.server()
cy.route('POST', 'URL', jsonresponse).as('myalias')
I appreciate any support.
Thanks!
You can use cy.intercept to match based on several things, including query parameters.
cy.intercept({
url: 'http://example.com/search*',
query: { q: 'expected terms' },
}, { fixture: 'myfixture' } )
If you need to match on the request body contents, you can use a route handler to specify.
cy.intercept('http://example.com/search*', (req) => {
if (req.body.contains('some string') {
req.reply({ statusCode: 200, fixture: 'myfixture' });
} else {
req.reply(); // not providing any input forwards the request as normal
}
});
Check out the cy.intercept documentation for more info.

Proxy error: Could not proxy request /payment from localhost:3000 to https://localhost:5000/

I am trying to create a stripe payment app using reactJS and expressJS, I am getting this error:
Proxy error: Could not proxy request /payment from localhost:3000 to https://localhost:5000/
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (EPROTO)
In package.json file I have set proxy as -
"proxy": "https://localhost:5000"
In my react component I have -
const onToken = token => {
axios({
url: "payment",
method: "post",
data: {
amount: priceForStripe,
token: token
}
})
.then(response => {
alert("succesful payment");
})
.catch(error => {
console.log("Payment Error: ", error);
alert(
"There was an issue with your payment! Please make sure you use the provided credit card."
);
});
};
In my server.js I have -
const stripe = require("stripe")("sk_test_...");
app.post("/payment", (req, res) => {
const body = {
source: req.body.token.id,
amount: req.body.amount,
currency: "usd"
};
stripe.charges.create(body, (stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).send({ error: stripeErr });
} else {
res.status(200).send({ success: stripeRes });
}
});
});
whenever I submit any payment I hit error -
I tried all method linked here but can't solve that issue. I heartily thank if anyone explain any solution of that problem.
Since your backend works fine without stripe, the 500 error indicates that stripe is the problem.
This is related to the information you are sending in the body of the stripe charges.create request. I think you are missing the customer.id.
This post arjunphp.com/node-stripe-express-js shows the charges.create request as
{ amount,
description: "Sample Charge",
currency: "usd",
customer: customer.id
}
As #CherryDT mentioned, first I set proxy to "proxy": "http://localhost:5000". Then I change my backend code as #Greg M suggested -
app.post("/payment", (req, res) => {
stripe.customers
.create({
email: req.body.email, // customer email, which user need to enter while making payment
source: req.body.token.id // token for the given card
})
.then(customer =>
stripe.charges.create({
// charge the customer
amount: req.body.amount,
description: "Sample Charge",
currency: "usd",
customer: customer.id
})
)
.then(charge => res.status(200).send({ success: "success" }));
});
That's it. My payment method works perfectly.
I think the proxy error is a red herring. The real issue is the parsing on your server, causing the 500.
It looks like by default Axios encodes the json for you (but you should double check the request). To access JSON encoded request body data in Express, you need to use the body-parser middleware.
See this answer for an example: How do I consume the JSON POST data in an Express application
I'm taking the exact react course from Andre. My solution was to start the backend server.
So whoever gets into this issue from the same course either try the answer above or:
npm start
or
yarn start

How can I access Google Fit data without logging in

I have a web page I am working on, I am wanting to use gapi to access my steps for the day. I do not want to log in every time, I want the page to log in automatically in the background, oAuth2 is required I believe but I can not get any further.
Based on code I've found online and using React with Hooks, I added ts ignore because it could not resolve gapi.
The issue I am having is that I get Login Required error
I've tried using Axios and doing it by API_KEY only. My knowledge on API's is growing but I thought just to access the data an API key would be enough providing I had registered the key in the API tools.
React.useEffect(() => {
const start = () => {
// 2. Initialize the JavaScript client library.
// #ts-ignore
gapi.client.init({
'apiKey': '<API_KEY>',
// clientId and scope are optional if auth is not required.
'clientId': '<CLIENT_ID>.apps.googleusercontent.com',
}).then(function() {
// 3. Initialize and make the API request.
// #ts-ignore
return gapi.client.request({
'path': 'https://www.googleapis.com/fitness/v1/users/<MY_GMAIL_ADDRESS>/dataset:aggregate',
'method': 'POST',
'body': {
"aggregateBy": [{
"dataTypeName": "com.google.step_count.delta",
"dataSourceId": "derived:com.google.step_count.delta:com.google.android.gms:estimated_steps"
}],
"bucketByTime": { "durationMillis": 86400000 },
"startTimeMillis": 1567983600000,
"endTimeMillis": 1568057160150
},
})
}).then(function(response) {
console.log(response.result);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};
// #ts-ignore
gapi.load('client', start);
}, []);
I just want to be able to return my steps in a JSON object preferably with Axios, if not using the gapi JS library using my React Application. Nothing fancy.
I appreciate this may not be possible but the docs and other questions on stack overflow just are not working for me and no one can answer me.

Can't access CakePHP API endpoint via ReactJS. Only through the browser

I am trying to build a REST API for my server via CakePHP. I thought I had it working as I can receive the JSON responses via the web browser however when trying to access the same route via ReactJS, the Controllers Action is not actually firing.
Reading the CakePHP docs I really should only have to implement these lines of code to get the API working (According to the docs) and I did:
/config/routes.php
Router::scope('/', function($routes) {
$routes->setExtensions(['json']);
$routes->resources('Users');
});
Here is the API Endpoint I want to hit:
`public function signUp() {
$file = fopen("error_log.txt", "w");
$txt = "firing endpoint";
$fwrite($file, $txt);
$fclose($file);
$response = $this->response;
$responseText = [
"status" => "200",
"message" => "User added successfully"
];
$response = $response->withType("application/json")
->withStringBody(json_encode($responseText));
return $response;
}`
Here I am successfully hitting that endpoint via the browser. My log message also appears in the error_log.txt file
Here is where I'm making a request via ReactJS:
handleRequest = () => {
console.log('making request');
axios({
method: 'get',
url: 'https://157.230.176.243/users/register.json',
data: {
email: this.state.email,
password: this.state.password
}
})
.then(function(response) {
console.log('got response');
console.log(response);
})
.catch(function(error) {
console.log('got error');
console.log(error);
})
.then(function(data) {
console.log('always executed');
console.log(data);
});
}
When I make this request via ReactJS I get a XHR failed loading: OPTIONS "https://157.230.176.243/users/register.json"
Also when making this request via ReactJS my log message does not get written to error_log.txt
Ok I finally figured out what was wrong. I have my React Development server running on
157.230.176.243:3001
and my CakePHP API served on that same server,
157.230.176.243
React didn't like it that I was passing the full URL of the API to the fetch()
call. I switched my React code to
url: "/users/register.json"
and it works fine.

How to get AngularJS Login form post reqest

Given the AngularJS example login form here, how can I know what post request is it sending when I click the Login button?
I try to use Chrome's Developer Tools Network tab, but all I got is a GET request.
Thanks!
If you look at the source code of the plunkr, you'll find this:
service.Login = function (username, password, callback) {
/* Dummy authentication for testing, uses $timeout to simulate api call
----------------------------------------------*/
$timeout(function(){
var response = { success: username === 'test' && password === 'test' };
if(!response.success) {
response.message = 'Username or password is incorrect';
}
callback(response);
}, 1000);
/* Use this for real authentication
----------------------------------------------*/
//$http.post('/api/authenticate', { username: username, password: password })
// .success(function (response) {
// callback(response);
// });
};
So the dummy authentication isn't sending any HTTP requests because it's a dummy timeout function which "simulates" an HTTP call.
The GET request you see there is an AJAX call to load the partial home.html view.

Resources