Dynamic encrypted paypal button? - javascript

so I am creating a website that needs to have a subscribe PayPal button. I am currently using the paypal button js, but it is very insecure, and people can change the amount they pay. So I am going to need to use the encrypted button, but I am not sure how to achieve this and still be able to change the price depending on the user. The reason I need to do this is so the user will be able to select different amounts of something. Say they can select anywhere from 1 to 50 points that would alter the price so if 1 point is 1 dollar and the user select 24 the subscribe button amount will have to be 24 dollars a month. Below is the current code for creating a non encrypted button. As a side question if anyone happens to know if it is important to keep your merchant id a secret. If so how would I do this?
$("#paypal-button").html(
'<script src="js/paypal-button.min.js?merchant=[Merchant ID]"' +
'data-button="subscribe"' +
'data-name="Custom Howloop Subscription"' +
'data-amount="' + roundTotal + '"' +
'data-recurrence="1"' +
'data-period="M"' +
'async' +
'> </script>'
);

A long time ago I tried to do something similar to this.
To my knowledge, there is no way to do it. You won't be able to simply change the values of the encrypted button and if it isn't encrypted, the user can change it and basically pay anything.
If you want to be able to safely and dynamically change values, I would suggest looking into their API/Express Checkout. That's what I did, and I am really glad that I did.
You can check everything before it is forwarded to PayPal, and I have never had an issue with that aspect of it (I pass the item ID and query my database to get the cost/etc and apply other checks to stop various issues.). And you can go through and apply any calculations that you need to for the price without an issue.
Otherwise, the only way I could think of is having multiple encrypted buttons for different prices. But that isn't very fun nor an optimal solution.
Edit: Now that I am not on mobile, here is a link to the Express Checkout Getting Started Guide.
Also, I do not believe that you need to worry about your Merchant ID being seen. It is used to process payments and I believe it can be seen in the transaction details.

YES THERE IS A WAY! Dont listen to the nay-sayers, i have recently successfully implemented encryption on dynamically created shopping cart information which was being injected into a empty form using php. I'm really planning to create a full tutorial because it seems that this information is RARE (i wonder why Paypal doesn't have a standard tutorial for this). I remember having days of stress because of this problem and almost a month later i happened to stumble on a tutorial provided here: https://www.stellarwebsolutions.com/en/articles/paypal_button_encryption_php.php
After some minor modifications i was able to use the PHP code to encrypt the data using my generated private keys and public certificates (make sure u have HTTPS on your website). Paypal was then able to successfully decrypt the information! (Oh boy you bet i did the happy dance)
Making sure data is valid only using IPN after payment is made is a very messy approach when u can avoid most tampering by doing custom encryption. Anyways until i buckle down and create a video tutorial good luck with the endeavor - on looking back i see how truly simple this process really is!

There's no way to do this without hosting the button details on PayPal's side. This would also happen in an old-style PayPal form integration where anyone can go into Chrome's Devtools and alter html form variables for example. As a workaround, you can implement one hosted subscribe button and have users change the quantity of the subscription. If your prices scale linearly with quantity of points then it'll work.

Related

Safely adding a customizable "tracking code" field to php web application

I have a small web application written in vanilla PHP with MySQL database, on which registered users are able to create custom profile pages.
Id like to add a textarea form field in the control panel, for users to add their custom tracking code (namely Facebook Pixel or Google Analytics) for their tracking purposes.
My question is, what is the correct way to add such functionality? I'm afraid letting my users to "inject" custom code would lead to security issues for my website. As far as i know the aforementioned tracking codes use regular JS/HTML for their tracking. If that is the case how to allow JS while restricting server side code, like PHP, from being executed?
Any help would be greatly appreciated.
The tracking code is always the same, apart from one or two elements. For instance, in a Google Tracking code the only variable element is a tracking ID in the format: UA-XXXXX-Y.
You could let the user select which type of tracking they want and let them only enter the tracking ID, and perhaps one more variable. You can easily check whether these have been entered in the correct format. From that you can generate the Javascript code yourself.
Alternatively, now that you know the code is always the same you could also use that to check what has been entered. Strip out any non-linguistical elements like space, and check it against your template: Only the ID's should be variable and you know their format.
However, I think this last method is less user-friendly, because it relies on the users to provide you with a rather exact copy of the code. That might be too difficult, and that will be your problem.

Making a Google Form which has a table for answer submission

I'd like to replace a parts requisition process at my workplace with a simple (and cheap to implement) electronic process, initiated using a Google Form. The problem is that I would like users to be able to enter multiple parts (along with associated info, e.g. quantities required, booking references etc.), but I want to do so without having to have multiple repeated questions.
I have researched this extensively and cannot find anything which fits the bill - my thoughts are to use Google Apps Script to create a table in the form which a user can fill-in. The closest I have found is something like this: Creating Form Elements Dynamically
The original paper form looks like the below - I would like the table to request the information as shown below in a similar format:
Thanks in advance!
EDIT! To make it clear, I'm happy to consider other solutions to run this process through an online interface - I have gone for Google Sheets/Forms in the first instance as they are already well integrated within my company and I have experience of them (setting-up triggers etc is pretty simple)
I understand the OP has probably long moved on from this problem. I however have done something along these lines in the past and thought I'd share my approach with the community.
I'll start with the premise Google forms are just good ol' plain HTML forms that users programmatically generate with their form builder. Therefore it's possible to traverse the as-built form and extract both submit location and all field names:
document.querySelectorAll('form').forEach((x) => {console.log(x.action)})```
document.querySelectorAll('[name^="entry."]').forEach((x) => {console.log(x.name + '=' + x.closest('[role="listitem"]').querySelector('[role="heading"]').innerText)})
The above snippet will give you an idea of what the components are.
All that's left after is to build a front end to your requirements with the framework of your choice (I used AngularJs at the peak of its popularity) and incorporate as much or as little UI and validations into it as you desire.
Here you've got the flexibility to either submit the whole thing as one JSON, or to parse it into individual fields and submit entries one by one, for purposes of this demo I opted for the easiest way but this thing surely's got the potential.

Displaying a JS var across different pages

This is a kind of difficult question because I'm not sure how to word it. I'm making a shopping cart website using HTML5 and JS and I've got most of it down, but need help with one important aspect.
At the moment my "Buy Now" buttons are in tags that link to 1 page where the user can enter his info and make the purchase, this page is called "checkout". I want this "checkout" page to display the price of the item he wishes to purchase.
For ex) The user clicks on an book worth $10.00 and clicks the buy now button. This button will send him to the confirmation page where it will show a fill form, but the page does not show the price of the item he is purchasing.
This is where my problem lies. I can't think of any solution for this besides making a different page for each product (I only have 9 products).
Also, if it isn't blatantly obvious, I'm still a beginner with JS. Any help would be appreciated in helping me figure out how to display the price on the "checkout" page of each specific item without creating 9 separate pages. Thank You.
If I understand correctly, you are asking how to store a variable in Javascript that can be retrieved by multiple pages.
The canonical way to do this is to use cookies. The native cookie library is rather messy, so I recommend using a cookie library, like this.
However, since your question is tagged html5, you might be open to the sessionStorage HTML5 solution for this, which is much simpler than cookies.
sessionStorage.setItem("price", 100);
var price = sessionStorage.getItem("price");
The best way is to use some serverside solution. The client sends his form to your server, where the form gets evaluated and an according html-page is rendered.
The only other way is either using cookies or local Storage - but that's rather ugly.
You definitely should read some tutorials about php and mysql, but I'll give you rough overview on how to achieve this.
You provide a form on your page like this:
<form method="post" action="your-serverside-phpscript-that-processes-your-form.php>
How many Ipads you wanna buy:<input type="number" name="ipads">
<button type="submit">
</form>
now on serverside your php-script can evaluate the form.
all formfields are stored in a $_POST array. ( $_POST["ipads"] ) gets the value the user entered in the form. You don't need to store these values in the database yet.
You evaluate the formvalues and create the checkout-page with the according data (total price). Now the user submits the checkout-form, which you again process and store in the database.
I won't write down (sry, too tired) how this serverside part works, there are tons of tuts out there, just search google for php+mysql.
Since you're wanting to persist this data all on the client-end, I would encourage you to check out Amplify.Store. In full disclosure, I am currently employed by the company behind it - but it's great, and free.
Saving data is easy:
amplify.store( 'cart', { name: 'Book Title', price: 10.99 } );
To access this a little later, you can simply call:
amplify.store( 'cart' );
This will return your object from which you can get all of the products currently loaded. Amplify will evaluate your system and determine which storage method is best, and use it. This removes all of the guess-work form your plate, and let's you just do what it is you're wanting to do.
Please understand that while it is convenient to persist data client-side, it is by no means secure. When dealing with transactions and issues of a financial nature, you should always keep figures out of the hands of the consumer.
Generally data like this is stored server-side, within a session, a database, or a combination of both. However, if you understand the risks, and your model permits this type of persistence, then by all means feel free to use this as a solution.

calculate number of working days on a rails form

I have two fields, 'from_date' and 'to_date' on my rails form. When a user enters the dates I have to display the number of working days i.e, exclude (sat, sun and a list of other official holidays in a database table).
Is this something that should be done in the client side javascript
Or is this something that should be done by making an ajax request to rails.
Can you tell me how I can accomplish this.
thanks much.
Depending on how often that feature would be used I'd opt for doing both, create a .js-file (or generate dynamically and just make sure rails caches it) and try it with javascript locally for instant gratification. Then make sure it's correct on the server side on saving.
The upside with doing it both on the client and on the server is that you may save some hassle when the guy can see it directly on the site without doing a request. But if they have javascript disabled it'll still work. And if it's anything important you should never trust what you get from a web form. :)
This patch might give you some ideas. https://rails.lighthouseapp.com/projects/8994/tickets/2304-add-concept-of-weekdays
You might be interested in business_time.

Server-side highscores for a Javascript-written game

I'm implementing a simple game in Javascript, and am interested in having an online highscores table for it, so that players can compete against one another. I've two concerns about this:
What is the simplest server-side program I need for this purpose? I don't need a full-fledged "web application", just something simple that gets POST requests with highscores, updates a database and sends back lists of scores. I'm familiar with Django. What are your suggestions?
How can I make the highscores table reasonably secure? I'm aware that making it bulletproof against competent and dedicated hackers is difficult, but I wouldn't want anyone with access to the Javascript sourcecode to be able to submit fictitious scores too simply. Any tools for this purpose?
It's going to be pretty hard to secure the high scores. I mean, it's not enough to ensure that it comes from your page, because if, say, the JavaScript function is submitHighScore(n) then they can always type javascript:submitHighScore(10000000) in the address bar on that page and have it work.
What comes to mind is perhaps some sort of hash function that generates specific codes that match certain levels in the game. When submitting the score it would also submit this hash, so users would have had to get to this level in order to get that equivalent score.
Another option would be for the game to pull in some kind of key that only works temporarily, so as you went along the key would change and then the score would be submitted to a central server intermittently.
Keep in mind that really determined individuals can always just track the data being sent to your data and decompile it.
You could go the Broderbund route and ask the player trivia questions which are validated server-side to ensure they really did pass the level they said they did...something like "What color was the monster in the previous level?"
To submit score securely, sign it (you'd also need to ensure that the score isn't faked before it's signed and sent, but that's another problem).
Hide a secret in JS code, and send highscore + hash(highscore + secret) to the server. The hash could be MD5/SHA1 — there are easy to find JS implementations.
Of course it won't stand anyone carefully analysing the JS code, but at least someone won't be able to submit fake highscore just by tampering with HTTP traffic.
On hiding stuff in JS:
You can't really hide it (it's ultimately futile like DRM), but you can try hard to obfuscate it and make debugging painful.
Don't put the secret as a literal in the source code - compute it at run time combining results of several functions, local and global-ish variables.
Minify all code, remove sourcemaps.
Add bits of code that don't do anything, but seem to be important, to make debugging more confusing.
Don't put anything in global scope, but do rely on shared mutable state by passing closures and arrays around.
Rely on Date and timers to cause race conditions to make your code produce wrong results if it's paused in the debugger (just don't make it too tight to allow it to run on slow machines).
If the game is deterministic (like a puzzle game), then users could submit highscore in form of a log of steps taken to win (user's input) that you'd replay on the server to calculate the score.
This would change attack from finding/emulating score-submitting function to witing AI or hacking the game itself to make it easier to play (but still within its basic rules).
1.) Any CGI script that can talk to a database and understand JSON, or other format of your choice, will do the work.
However, if you're familiar with Django, building your server on top of Django would be the most simple, in the sense of what you have to learn and how much application code you have to write. Seemingly simple CGI script can turn out rather complex if you write it from scratch.
I found django-piston to be a handy Django app to quickly write a REST-style API server. It supports JSON so it should be easy to interface with your JavaScript game.
2.) The most casual cracker will go for a replay attack and its variants: peek at the page source and execute a JavaScript function, intercept HTTP requests and resend it (should be easy with a Firefox add-on like Tamper Data).
To counteract the former, you can obfuscate the source code and HTTP body;
Minify the JavaScript code
Encode the message you send to the server with Base64 or other encoding algorithm
The latter can be prevented by requiring all update requests to include an one-time password ("session token" in the Wikipedia article) that was recently acquired from the server.
I am thinking about this myself. What seems to be the most reasonable solution to me is this:
1) Sessions, to disallow tampering with the scoretable outside the game.
2) Log every action in the game and send it to the score server. The server will then calculate if those actions actually give such score. If you also log the time spent playing the game, you can further minimize the chance of an attacker to bother himself enough to break your game. This will also enable you to make a replay script like Arcade servers with hi-score tables have and in case of a suspicious score, you can watch the replay and decide for yourself if the score is real. The cheater would have to use a clever bot to play your game - and unless you have a game for real prizes, noone will try that hard.
If the cheater won't even analyze your code, sessions will stop him. If he reads your code, he would quickly break anything similar to hashed scores, secrets, tokens and whatsoever. But if you make the game-logging script thorough enough, he will give up.
In answer to your question:
1.) This depends on your environment and coding preference. PHP, Python, ASP.NET are a few that come to mind. Sense you already know Python (from your profile) you can use a Python CGI script to do this or use one of the many frameworks for Python (Zope, Django, Pylons,...).
see: http://www.python.org/doc/essays/ppt/sd99east/index.htm
for info on Python CGI.
2.) A few tricks for security: (none or full-proof)
Hidden Text Box in HTML with encoded value that server checks to match a cookie to ensure high score comes from your page.
Server Script only accepts values from a specific domain
You could use a combination of one of the methods above, as well as simply requiring the user to be registered to be able to post high scores. Non registered users could view their current score compared to existing high scores, but in order to post your high score online, you must have already logged in with your registered account, or provide it when the app goes to update the score online.
A simple message along the lines of "Your high score is X, and ranks ### in the high score table. To post this score online, please register with us first".
The better I think, is to make the calculation of the score directly into the python files of your django app.
Instead of calculate it in the javascript file. You send the datas to compare with your data basis with a POST request, then you calculate the score and you store it in your data basis. Like this, you don't make circulate the score across the web to your servers. Which is completely safe because you are only doing local stuffs.

Categories