Can I send a Stripe charge request directly from the frontend? - javascript

I am wondering if I can send a Stripe request directly from my front-end, because I don't have a back-end. Please note that security isn't an issue, because I won't deploy the project or even use it in any way shape or form.
I am thinking of using axios instead of curl, and it should look like something like this:
On the Stripe official doc, they use curl on the back-end
I am also wondering if there's any other key I need to pass. There's a secret key and a publishable key. I am thinking the publishable key is not needed. Also, do I need to activate my account in order for it to work? I don't plan to use it outside of pet projects.
axios({
method: 'post',
url: 'https://api.stripe.com/v1/charges',
header: {
Authorization: 'sk_test_IvnLvlpEpskxJA8u7eEsAOBr00e7fmPyMZ'
},
data: {
amount: '999',
currency: 'cad',
description: '',
source: 'tok_visa'
}
});
I want the same result a curl request would yield.

You should not be making this call client-side, both for Security reasons obviously but also because you'd have to make the raw request and handle error handling and such.
Instead, you should use one of Stripe's official client libraries. Those run server-side, but it doesn't mean you need a separate server. You can just run the code locally on your computer for example by building a PHP script that interacts with your client-side code in the browser.
Another alternative would be to use Checkout as there's a client-side-only integration that only requires some javascript. See the docs here.

Related

Safe to call WooCommerce, WordPress and CoCart endpoints in frontend? I need your opinion

Question
I got a question about security. I am building a mobile webshop in Flutter. Is it bad to make those API calls in the frontend? Should I make a separate backend for it in Node for example?
I have also read that you can 'create' your own endpoints in WordPress with PHP. What about that? Does that make it any safer or not?
What endpoints do I use?
There is an existing WooCommerce API to retrieve products, get categories, and create orders on the WooCommerce API. On the CoCart API, you can retrieve the cart, add to the cart, delete the cart, etc...
For the Mollie payment APIs, I think it is better to make a backend.
My take on it
I think it is fine to call those endpoints in the front end. I have seen Flutter packages for WooCommerce to call those endpoints. Yes, I do send the basic auth in the headers... so I am not sure how 'dangerous' that is.
But on the other side. What can the 'hacker' do? They can see all the products, that is fine I guess. I am not sure if they can create orders... They cannot steal money at least :)
Reference code
For reference, here is a piece of code when calling an endpoint:
Future<Product> getProductById(int productId) async {
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
print(basicAuth);
var response = await http.get(
Uri.parse(
'https://websitename/wp-json/wc/v3/products/${productId}'),
headers: <String, String>{'Authorization': basicAuth});
if (response.statusCode == 200) {
return Product.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed');
}
}
Let me know your opinion!
When talking about security main question is what goes over the network request. If your username & password from code above is something to keep secret, that can't be on client side.
If you sent code to user, user got it and can check what's happening while tracing network requests.
You can always skip the UI, debug network request and take all the details that were sent over that request and send those requests with cURL or anything else. Yet client must authenticate somehow, and that's a wide topic from "unlisted" URLs where you just need to have exact "random id" to get to the resource (e.g. youtube's or many file sharing services use that as "unlisted" link, which means this won't be in search results but if you have exact link, you will get into the resource) to oAuth2, which you can learn more about here and
you could check this post too which covers several methods of token-based authentication.

Making POST request from ReactJS app built on WordPress

I'm building a ReactJS app on top of a WordPress backend. The React App is running on the same domain, embedded in the WordPress site. Most of the tutorials I've been following cover how to get data from WordPress to React. I've been successful at this, but need to figure out how to submit data from my React app to WordPress (preferably via the REST API).
This will be a custom admin page for logged in editors, either available in the admin panel or from the front-end.
As an example to create a post, I'm naively trying the following function:
saveGrid() {
const url = "/wp-json/wp/v2/posts";
const body = JSON.stringify({
"title":"internet",
"content":"teapot"
});
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:body
});
}
I get back a 401 unauthorized response. What is the easiest way to authorize myself for a POST submission (secure solution preferred)?
It looks like you're on the right track.
A quick read of this: https://apppresser.com/wp-api-post-submission/
shows me that all you're missing is a "nonce" in order for the WP API to recognise and validate your request successfully.
In the guide above, the dev created a JS written in JQuery that sends XHR/AJAX requests to the WP API and in their plugin.php they enqueue and localize the script with some variables from WP to help with the request inside the JS.
The takeaway here is that they used wp_create_nonce('wp_rest')and assigned this to a localized variable nonce so they could easily reference that later inside the JS and assign nonce to their X-WP-Nonce header inside the request!
If you look into this further you might find a suitable alternative for you that will work as I'm not entirely sure how you're loading your JSX files but this guide may come in handy for you to enqueue your JSX scripts/files: http://blog.milandinic.com/2015/12/01/using-react-jsx-in-wordpress/
More information
https://codex.wordpress.org/Function_Reference/wp_localize_script
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
I was able to solve this problem by, instead of having a straight post request from React, using a Jquery AJAX submission outside of React that uses data from a form inside React. This caused the request to contain the necessary cookies (I don't understand exactly why this is the case)

How to make a REST GET request (with authentication) and parse the result in javascript?

Due to circumstances beyond my control, Javascript is the only language option available for me. I'm a beginner and am not even sure if I'm approaching the problem in a "recommended" manner.
Simply put, a customer has setup a MarkLogicDB server online and has given me read-only access. I can query the server with the HTTP GET protocol to return an XML document that has to be parsed. I've been able to create a curl command to return the data I need (example below);
curl --anyauth --user USERNAME:PASSWORD \
-X GET \
http://test.com:8020/v1/documents?uri=/path/to/file.xml
The above returns the requested XML file. Can someone please show me how I could convert the above to javascript code? Additionally, how would I parse the data? Let's say I want to get all the info from a certain element or attribute. How can this be accomplished?
This would be trivial for me to do in Java/.NET, but after reading plenty of online tutorials on Javascript, my head is spinning. Every tutorial talks about web-browsers, but I'm doing this on a server environment (The parse.com CloudCode). There isn't any UI or HTML involved. For debugging, I just read the logs created with console.log().
https://parse.com/docs/cloud_code_guide#networking seems pretty clear, as far as it goes.
Parse.Cloud.httpRequest({
url: 'http://test.com:8020/v1/documents',
params: {
uri : '/path/to/file.xml'
},
success: function(httpResponse) {
console.log(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
}
});
But you'll also need authentication. The Parse.Cloud.httpRequest docs don't include any examples for that. If you have support with that vendor, ask the vendor about digest authentication.
If you're stuck you might try adding user and password to the httpRequest params and see what happens. It might work, if the developers of this stack followed the XMLHttpRequest convention.
Failing support from the vendor and existing functionality, you'll have to implement authentication yourself, in JavaScript. This works by generating strings that go into the request headers. These resources should help:
http://en.wikipedia.org/wiki/Digest_access_authentication
http://en.wikipedia.org/wiki/Basic_access_authentication
Basic auth is much easier to implement, but I'd recommend using digest for security reasons. If your HTTPServer doesn't support that, try to get the configuration changed.

How to post Facebook Score using JS SDK, without hardcoding the app access token?

I'm trying to post a score using the JS SDK. Here's the code that I'm using:
FB.api("/[USER_ID]/scores", 'post', {score:score, access_token:"APP_ACCESS_TOKEN"}, function(response){
if (!response || response.error) {
log(response);
} else {
log(response);
}
});
However, I need to do this without hardcoding the APP_ACCESS_TOKEN. Any idea on how to do it using the JS SDK?
/me/ refers to the current user - when using the app access token there is no 'current' user - you're acting as the app - make the request to /[USER ID]/scores using the app access token
You can grab access_token through JS by using FB.getLoginStatus. More can be found in the doc.
.
There is no way, that I know of.
And, nor should there be, when you consider that the App will only have one app access_token.
Think of it like your app secret, keep it safe!
Especially when you consider how you get the access_token to start with, just by making a formatted request to FB with your ID and App Secret.
If you put that client side, then ANYONE could grab it and do stuff on behalf of your app!!
I would suggest one of two things:
Try making a call to /me/scores, and use the normal access token.
Even though the API docs don't suggest this being possible, you never know.
OR
2. Encapsulate it as an AJAX call to your server, and make the Graph call from there.
Sucks, but there seems to be a few things that aren't quite designed to work on the client side yet. :-/

Using Only Javascript To Shrink URLs Using The Bit.ly API

I'm playing a bit with Javascript these days... I was shrinking some URLs using bit.ly to tweet them, then I started to think on a automated process that could use their API to shrink the URLs I wanted, then I looked up on their documentation, and I saw that they only support PHP(with some Javascript), but there is anyway that I could make this using only Javascript?
Here is an example how to get a shortened URL with Bitly API and jQuery, no server side code required.
function get_short_url(long_url, login, api_key, func)
{
$.getJSON(
"http://api.bitly.com/v3/shorten?callback=?",
{
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url
},
function(response)
{
func(response.data.url);
}
);
}
The following code could be used to get a short URL:
/*
Sign up for Bitly account at
https://bitly.com/a/sign_up
and upon completion visit
https://bitly.com/a/your_api_key/
to get "login" and "api_key" values
*/
var login = "LOGIN_HERE";
var api_key = "API_KEY_HERE";
var long_url = "http://www.kozlenko.info";
get_short_url(long_url, login, api_key, function(short_url) {
console.log(short_url);
});
Depending on where the JavaScript is executing, you could always use the bit.ly REST API:
http://code.google.com/p/bitly-api/wiki/ApiDocumentation
via XmlHttpRequest, for example:
http://api.bit.ly/v3/shorten?login=bitlyapidemo&apiKey=R_0da49e0a9118ff35f52f629d2d71bf07&longUrl=http%3A%2F%2Fbetaworks.com%2F&format=json
From the developer best practises page on bitly:
To ensure the security of your API key and/or OAuth access token, we strongly suggest that you make requests to the bitly API server-side whenever possible.
Any requests to the bitly API made via client-side Javascript present the risk of your OAuth token or API key being compromised, but there are steps you can take to partially mitigate this risk. Most importantly, never include your api_key or access_token inline in the page. Keep any references to your api_key or access_token in code that is contained in external javascript files which are included in the page. For additional security, don't have the key or token itself contained anywhere in your javascript code, but rather make an ajax call to load it, and keep it in a variable stored in a privately scoped method. For an example of this implementation, please see our sample html and included javascript files.

Categories

Resources