Introduction
In this tutorial you will learn how to import and use the PayPal API plug-in. This plug-in makes it easier to add secure payments into your Appery.io mobile app and trigger any PayPal REST API.
By using the PayPal, the world-famous payment system, you can add the ability to charge users for a certain amount of money – this way you can build your mobile shop with online payment functionality.
This tutorial will also show how to create Server Code script to implement server side authentication which is totally secure – your app will not contain any sensitive data such as client secret or token.
The plug-in implements this flow provided by PayPal.
Before you begin
Tutorial level: intermediate.
Before using the PayPal API you will need to sign up for a free account: http://developer.paypal.com/. Then you should create your app on the PayPal side and you will get an API key to use.
Create a new app
To start, you are going to create a new app.
- Click “Create new app”. For app name, enter:
PayPal App
(use any name you want) and click “Create” . - When the app builder loads, you will see the
Start
page. Every new app has a default page. You can open the page by going toPages > startScreen
.
Next you are going to import the PayPal API
plug-in.
Importing the plug-in
- To import the plug-in, click
Create New > From Plug-in
:
- Check the box for
PayPal API
:
- Click “Import selected plug-ins”.
- Select
PayPal_Home
page as start page. - Click “Apply settings”.
That’s all for now.
Creating the database
- Create a new database called
PayPalDB
. - Inside the database, create a collection called
Credentials
. - Inside the
Credentials
collection, create two columns called:key
andkeyValue
(bothString
type). - Copy the created database ID and paste it to the
PayPal_Settings > database_id
(under theServices
folder) in the Visual Builder.
Token will be stored to the collection via Server Code, so there is nothing more to add here. Here is how your collection should look:
Creating the Secure Proxy
- Click on “Secure Proxy” tab or go to http://appery.io/proxy
- Click “Create new proxy”, name the proxy
PayPalProxy
. Click “Create”. - In the proxy setting page check “Use proxy + store sensitive (private) data in database”.
- For
Database
selectPayPalDB
. - For
Collection
selectCredentials
. - For
Key column
selectkey
and forValue column
selectkeyValue
. - Click “Save”.
Now you need to tell the REST services to use this proxy:
- In the app builder, open
Services > PayPal_Complete_Payment
. - Check
Use Appery.io proxy
and select the proxy that you just created. If you don’t see the proxy click the refresh button. - Repeat the same for
PayPal_Create_Payment
service.
When Secure Proxy is turned on for REST Services, token
parameter will be automatically substituted with actual value on the server side. According to this, all you need to do for calling any PayPal REST API is turn on created proxy for that REST Service. The token value that was previously retrieved via the Server Code script will be automatically added to the REST.
Creating the Server Code script
This plug-in uses Server Code script to authenticate with PayPal. Script will return Success or Error events and it will be triggered once the app is loaded.
- Create a new Server Code script called
PayPalAuth
. - Paste the following code to the script body:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283var database_id = request.get("database_id");var paypal_url_api = request.get("paypal_url_api");var tokenID;var tokenUpdatedTime;var COLLECTION_NAME = 'Credentials';var CLIENT_SECRET_ENCODED = '<YOUR CLIENT SECRET>';//Retrieving collection with token and client secretvar collection = Collection.query(database_id, COLLECTION_NAME);//Searching for token object id and its last updated timefor (var i = 0; i < collection.length; i++) {if (collection[i].key == 'token') {tokenID = collection[i]._id;tokenUpdatedTime = collection[i]._updatedAt;break;}}//If token already exists, then check if it's expiredif (tokenID) {var updatedTime = new Date(tokenUpdatedTime.$date);var now = new Date();console.log("Token exists. It's alive for " + (Math.round((now - updatedTime)) / 1000).toFixed(0) + ' sec');//Check if token is expiredif ((Math.round((now - updatedTime)) / 1000).toFixed(0) >= 28800) {console.log('Token expired, issuing new one');//Sending XHR for new tokensendXHR();} else {//Token exists and it's not expired so just send a successconsole.log("Token exists and it's not expired. ");response.success({'Message': 'Authorization successful. Token still alive.'}, 'application/json');}function sendXHR() {var XHRResponse = XHR2.send("POST", paypal_url_api + "/v1/oauth2/token", {"headers": {'Authorization': 'Basic ' + CLIENT_SECRET_ENCODED,'Content-Type': 'application/x-www-form-urlencoded','Accept': 'application/json'},'body': 'grant_type=client_credentials'});var status = XHRResponse.status + '';//If XHR response status doesn't start from 2 digitsif (status.charAt(0) != '2') {response.error({'Message':'Error during authorization. ' + 'Status: ' + status});} else {try { //If we're here and tokenID exists, we should update itif (tokenID) {Collection.updateObject(database_id, COLLECTION_NAME, tokenID, {"key": "token","keyValue": XHRResponse.body.access_token});response.success({'Message': 'Authorization successful. Token updated.'}, 'application/json');} else {//If we're here, token doesn't exist so let's create itCollection.createObject(database_id, COLLECTION_NAME, {"key": "token","keyValue": XHRResponse.body.access_token});response.success({'Message': 'Authorization successful. Token stored in the database.'}, 'application/json');}} catch (e) {response.error({'Message':'Error during saving / updating token. ' + e}, 'application/json')}}}} else {console.log('Token does not exist. Creating new one');//If there is no token, let's issue onesendXHR();} - On the line 6, replace
<YOUR CLIENT SECRET>
with your PayPal appclient ID
andsecret
separated by a colon and encoded as base64. For example, you should combine the following string:1ATQ8cxB02m5DRQ7xDOFbazqISjUUhCsXVjkMlmYkpOqw1oxg4uCqkvhJEruF:EBYoDSDQa_gGBADGWLdooA3hd5qBVk7xvfKZWio4Bosajr4p8JZwdi_PJleD - Copy the
Service URL
from theREST information
tab and paste it to thePayPal_Settings > auth_script_url
(under theServices
folder) in the Visual Builder.
Your Server Code script should look like the following:
Filling return and cancel URLs
One more very minimal setup step is required – fill the return_url
and cancel_url
parameters in PayPal_Settings
. This plug-in doesn’t handle payment canceling in any special way, so the URLs will be the same. But if you want to handle payment cancels you can use a unique URL for cancel_url
. Change <YOUR_APP_ID>
to your Appery.io app ID (copy it from the address bar) and paste the following string to return_url
and cancel_url
parameters:
1 |
http://appery.io/app/view/<YOUR_APP_ID>/app/PayPal_Payment_Details.html |
If you’re using libraries version below 3.0, the
URL
will look as following:
1 http://appery.io/app/view/<YOUR_APP_ID>/PayPal_Payment_Details.html
Here is how your PayPal_Settings
should look:
Running the app
That’s all you need to do. You can now run the app by clicking the “TEST” button (using frame isn’t permitted due to PayPal security reasons, so launch the app without frame).
Once the app is loaded, the Server Code script will be triggered. Usually it’s a few seconds until the Server Code script will return Success.
The home page contains the predefined amount of money (6.99) and a Select
component to change the currency (USD or EUR):
Click “Make Payment” to create a payment. Assume that user just clicked “Buy” in your online shop. Once the payment is created, PayPal website will be opened. On this page, the buyer credentials should be entered. You can use one of the PayPal test accounts to test the app.
Once the payment is approved on behalf of the buyer, the PayPal_Payment_Details
page will be opened. The details of payment will be shown here: