Migrating from rest_proxy.php to CORS
When UltraCart first introduced checkout REST APIs, browsers could only talk to the same server that the page resided on. Because of this restriction, a proxy was necessary to take the requests and relay them to the UltraCart service. To accomplish this a script known as rest_proxy.php was created. This PHP script utilized cURL to perform the proxying. The script served it's purpose, but there is a far better option supported by all browsers known as CORS (Cross Origin Request Serving). CORS allows your REST checkouts to talk directly to the UltraCart server without proxying through your server. Here are some of the benefits of migrating away from rest_proxy.php.
- No longer a need for PHP on your server if none of your other coded is PHP.
- No breakage due to PHP/cURL upgrades performed on the server.
- Reduced load on your web server.
- No change of your web server's IP being blocked if malicious traffic goes through the proxy.
- Faster checkout experience for your customers.
- Easier to troubleshoot using browser developer tools.
The upgrade is a fairly simple process. Most of you built your checkout using sample code that we provided on GitHub. Let's take a look at the typical top of a file named cart_1.0.js.
// Things you need to set var merchantId = 'DEMO'; var usingProxy = true; var proxyPath = '/scripts/rest_proxy.php'; var restUrl = usingProxy ? (proxyPath + "?_url=/rest") : "/rest";
All we have to do is modify the code to look like this:
// Things you need to set var merchantId = 'DEMO'; var restUrl = "https://api.ultracart.com/rest";
Basically you're changing your restUrl so point directly at UltraCart. The jQuery library will automatically detect that this is a CORS request and behave accordingly.