• No results found

SEEM4540 Open Systems for E-Commerce Lecture 06 Online Payment

N/A
N/A
Protected

Academic year: 2021

Share "SEEM4540 Open Systems for E-Commerce Lecture 06 Online Payment"

Copied!
23
0
0

Loading.... (view fulltext now)

Full text

(1)

SEEM4540

Open Systems for

E-Commerce

Lecture 06 – Online Payment

PayPal

PayPal is an American based e-commerce business allowing payments

and money transfers to be made through the Internet.

In 1998, a company called Confinity (founded by Max Levchin, Peter

Thiel, Luke Nosek, and Ken Howery) is established. PayPal was

(2)

PayPal for Developer

PayPal provides four ways for you to interact with its database:

Predefined Buttons

Simply add some PayPal buttons on your web page.

REST

We will discuss this in this lecture note

Mobile SDK

For iOS (Objective C) and Android (Java) programmers

We will skip this in this course.

Classical APIs

It make use of non-RESTful interfaces to provide payment

solutions. This is the traditional way to connect to PayPal.

We will skip this in this course.

Copyright (c) 2012. Gabriel Fung. All rights reserved.

PayPal Payment

Copyright (c) 2012. Gabriel Fung. All rights reserved.

A Shop Buyer

1. Checkout (e.g., after adding items to shopping cart.)

PayPal

2. Request an access-token (based on a registered App ID)

3. Reply

4. Send buyer information (use access-token as authentication)

5. Reply 6. Redirect to PayPal Payment page

7. Authorize payment

8. Reply user action (authorize or not) 9. Complete payment

10. Reply 11. Reply

(3)

Using PayPal

To use PayPal, we have to register two accounts:

PayPal account

Used for creating our own application. You will granted for all

developer tools as well.

https://www.paypal.com/

PayPal sandbox account

Used for doing testing. Obviously, you do not want to conduct real

transaction and use your own money for testing purpose. That’s

why we need it.

https://www.sandbox.paypal.com/

Documentation:

https://developer.paypal.com/docs/

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Sandbox

In computer security, a sandbox is a security mechanism for

separating running programs. It is often used to execute

untested code, or untrusted programs from unverified third

parties, suppliers, untrusted users and untrusted websites.

(4)

Developer Tools

To create app, we need to go to the developer side:

https://developer.paypal.com/developer

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Developer Interface (cont’d)

(5)

Using PayPal with REST API

General steps:

1. 

Create a PayPal application (a.k.a. PayPal app) from the online

PayPal developer interface.

2. 

In your program, connect to your PayPal application and obtain

an access token dynamically.

3. 

In your program, make API calls based on the dynamically

generated access token.

Copyright (c) 2012. Gabriel Fung. All rights reserved.

(6)

Create a PayPal App (cont’d)

Copyright (c) 2012. Gabriel Fung. All rights reserved.

A sample screen shot

Create a PayPal App (cont’d)

(7)

Create a PayPal App (cont’d)

A sample screen shot

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Client ID and Secret are used to obtain your access token

Get an Access Token (cont’d)

REST API:

https://developer.paypal.com/docs/api/

(8)

cURL

A software project providing a library and a command-line tool

for transferring data using various protocols.

Some people pronounce it as “see-U-R-L”, whereas some

pronounce it as “crew”.

The cURL project produces two products, libcurl and cURL. It

was first released in 1997.

For example, you may type this in a command line (for Linux

and Mac OS):

curl www.cuhk.edu.hk

Copyright (c) 2012. Gabriel Fung. All rights reserved.

cURL (cont’d)

In PayPal API, you may see:

It means:

The URL is https://api.sandbox.paypal.com/v1/……

You should set the header (–H) to “Accept: application/json” and

“Accept-Language: en_US” (Note: there are two –H)

You should set the “Basic Authorization mode” (–u) with username

as <Client-ID> and Password as <Secret>

(9)

PayPal PHP SDK

PayPal now provides a full-featured SDK for PHP Developers!

PayPal PHP SDK is the official Open Source PHP SDK for

supporting PayPal Rest APIs. Checkout all the supporting

documents, samples, codebase from:

http://paypal.github.io/PayPal-PHP-SDK/

Copyright (c) 2012. Gabriel Fung. All rights reserved.

PayPal PHP SDK Installation

Follow the instruction here:

https://github.com/paypal/PayPal-PHP-SDK/wiki/Installation-Direct-Download

(10)

PayPal PHP SDK – Your First Call

To make sure you have installed everything without problem,

please write a PHP file with the following content:

Note: they are are based on the instructions in:

https://github.com/paypal/PayPal-PHP-SDK/wiki/Making-First-Call

<?php

require __DIR__ . '/PayPal-PHP-SDK/autoload.php’;

$clientId = "xxxxxxxx";

$secret = "xxxxxxxxx”;

$apiContext = new \PayPal\Rest\ApiContext(

new \PayPal\Auth\OAuthTokenCredential($clientId, $secret)

);

Copyright (c) 2012. Gabriel Fung. All rights reserved.

PayPal PHP SDK – Your First Call (2)

$creditCard = new \PayPal\Api\CreditCard();

$creditCard->setType("visa")

->setNumber("4417119669820331")

->setExpireMonth("11")

->setExpireYear("2019")

->setCvv2("012")

->setFirstName("Joe")

->setLastName("Shopper");

try {

$creditCard->create($apiContext);

echo $creditCard;

}

catch (\PayPal\Exception\PayPalConnectionException $ex) {

echo $ex->getData();

}

?>

(11)

Make API Calls

With a valid access token, you’re ready to make a request to

web services via REST API interface.

In the following, we will demonstrate how to make a payment

transaction.

We need to create three pages:

1. 

Process Payment page

2. 

Confirm Payment page

3. 

Cancel Payment page

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Process Payment – payment_process.php (1)

<?php

require __DIR__.'/PayPal-PHP-SDK/autoload.php'; // include the SDK use PayPal\Api\Amount; // include the classes

(12)

Process Payment – payment_process.php (2)

$payer = new Payer(); // create a payer $payer->setPaymentMethod("paypal");

$item1 = new Item(); // your items. Note: they should be get dynamically! $item1->setName('Coffee Bean') // for demonstration, we hard-code them ->setCurrency('HKD')

->setQuantity(1) ->setPrice(75); $item2 = new Item();

$item2->setName('Chinese Tea') ->setCurrency('HKD')

->setQuantity(3) ->setPrice(200);

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Process Payment – payment_process.php (3)

$itemList = new ItemList(); // combine all items into a list $itemList->setItems(array($item1, $item2));

$details = new Details(); // add other details, such as shipping $details->setShipping(200)

->setSubtotal(675); // make sure the amount (without shipping) is correct! $amount = new Amount();

$amount->setCurrency("HKD")

->setTotal(875) // make sure the amount (included shipping) is correct! ->setDetails($details);

$transaction = new Transaction(); $transaction->setAmount($amount) ->setItemList($itemList)

(13)

Process Payment – payment_process.php (4)

$baseUrl = "http://www1.se.cuhk.edu.hk/~xxx/yyyy/"; $redirectUrls = new RedirectUrls();

$redirectUrls->setReturnUrl("$baseUrl/payment_confirm.php") // make sure it exists ->setCancelUrl("$baseUrl/payment_cancel.php"); // make sure it exists

$payment = new Payment(); $payment->setIntent("sale") ->setPayer($payer)

->setRedirectUrls($redirectUrls) ->setTransactions(array($transaction));

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Process Payment – payment_process.php (5)

$request = clone $payment; // clone the payment object for debugging if necessary try {

(14)

Process Payment – A Sample Output

A sample output

Copyright (c) 2012. Gabriel Fung. All rights reserved.

It will redirect to your cancel page Use the sandbox account for payment. Not your real account.

Process Payment – A Sample Output (cont’d)

A sample output

(15)

Process Payment – Funny Issue 1

When I was preparing this lecture note (in 2015 Semester), I

have the following error in the whole night.

Copyright (c) 2012. Gabriel Fung. All rights reserved.

After spending 3 hours for debugging, I give up. It turns out that it is PayPal sandbox is down…

Not my problem… (There was news about this as well…)

Process Payment – Funny Issue 2

When I was preparing this lecture note (in 2016 Semester), I

have the following error:

SSL operation failed with code 1. OpenSSL Error messages:

(16)

Cancel Payment

To write a cancel payment page is very simple. For example:

1. 

Create a file in paypal/payment_cancel.php

2. 

Write the following content:

You have canceled your payment

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Confirm Payment – payment_confirm.php (1)

<?php

require __DIR__.'/PayPal-PHP-SDK/autoload.php'; use PayPal\Api\ExecutePayment;

use PayPal\Api\Payment;

use PayPal\Api\PaymentExecution;

$clientId = "xxxxxx"; // set your client ID and Secret $secret = "xxxxxxxx";

$apiContext = new \PayPal\Rest\ApiContext(

new \PayPal\Auth\OAuthTokenCredential($clientId, $secret) // get the access token );

$paymentId = $_GET['paymentId'];

$payment = Payment::get($paymentId, $apiContext); $execution = new PaymentExecution();

(17)

Confirm Payment – payment_confirm.php (2)

try{

$result = $payment->execute($execution, $apiContext); try{

$payment = Payment::get($paymentId, $apiContext); echo "Thank you for your payment";

}

catch(Exception $ex){ …

} }

catch (Exception $ex) { ….

} ?>

Copyright (c) 2012. Gabriel Fung. All rights reserved.

PayPal Payment

(18)

Shopping Cart

Now the only thing we left is to create a shopping cart for

people to buy products.

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Basic Shopping Cart

Before we create a shopping cart, we should have a page (or

some pages) display our products

A basic shopping cart should contains at least the following

components:

Add items to cart

Remove items from cart

(19)

Display Products

Sample code snap (e.g., in shoppint-cart/index.php)

<?php session_start(); if(!$_SESSION['shoppingCart']){ $_SESSION['shoppingCart'] = array(); } ?> <!DOCTYPE html> <html> <head></head> <body> <h2>Products</h2> <?php $products = json_decode(file_get_contents("http://xxx/api/products/")); foreach($products as $product){ ?>

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Display Products (cont’d)

<div>

Name: <?php echo $product->name ?> Sticker<br> Price: $<?php echo $product->price ?><br>

<form method="post" action="/shopping-cart/add.php">

<input type="hidden" name="productID" value="<?php echo $product->productID ?>"> We need to create

(20)

Display Products (cont’d)

A sample interface

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Add Items to Cart

Sample code snap (e.g., in shoppint-cart/add.php)

session_start(); if(!array_key_exists($_REQUEST['productID'], $_SESSION['shoppingCart'])){ $_SESSION['shoppingCart'][$_REQUEST['productID']] = array( name => $_REQUEST['name'], price => $_REQUEST['price'], quantity => 1 ); } else{ $_SESSION['shoppingCart'][$_REQUEST['productID']]['quantity']++; } header("location: /shopping-cart/");

(21)

Remove Items from Cart

Sample code snap (e.g., continue shoppint-cart/index.php)

<h2>Your shopping cart</h2> <?php

$totalPrice = 0;

foreach($_SESSION['shoppingCart'] as $productID=>$product){ ?>

Name: <?php echo $product['name'] ?><br> Quantity: <?php echo $product['quantity'] ?><br> Unit Price: $<?php echo $product['price'] ?><br>

Sub-total: $<?php echo $product['price']*$product['quantity'] ?><br> <form method="post" action="/shopping-cart/remove.php">

<input type="hidden" name="productID" value="<?php echo $productID ?>"> <input type="submit" name="submitButton" value="Remove">

</form> <hr>

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Remove Items from Cart (cont’d)

<?php

$totalPrice += $product['price']*$product['quantity']; }

if($totalPrice > 0){ ?>

(22)

Remove Items from Cart (cont’d)

Sample code snap (e.g., continue shoppint-cart/remove.php)

<?php

session_start();

unset($_SESSION['shoppingCart'][$_REQUEST['productID']]); header("location: /shopping-cart/");

?>

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Remove Items from Cart (cont’d)

(23)

Checkout

Sample code snap (e.g., continue shoppint-cart/checkout.php)

session_start(); $items = array(); $totalPrice = 0;

foreach($_SESSION['shoppingCart'] as $productID=>$product){ // create the items

}

$clientId = "..."; $secret = "...”;

// similar to previous examples

Copyright (c) 2012. Gabriel Fung. All rights reserved.

Checkout (cont’d)

References

Related documents

The Service will use its best efforts to research and correct the returned payment and return it to your Payee, or void the payment and credit your Payment Account.. You may

To enroll in an online payment option or to receive e-bills from your online banking or bill payment site, please check with your institution to make sure they offer this

After sending the automatic payment request, verify the process by monitoring your account through Online Banking.. Automatic

a fixed rate mortgage, the only change in your payment would result from changes in your taxes and insurance, if you have an escrow account with your loan servicer.. If you have an

On your Home page (Figure 6) or from the Manage My Account link, select the My Payment Methods option:..

To test the redirect, simply submit the redirect form from your website, if your payment page appears with all the transaction and customer data in the page then

Once your merchant account has been established, verify with your bank that your account has been set up to process online payments using VeriSign Payment Services as the

Our e-commerce platform accepts global payments for your online and mobile webshops and supports a wide range of international and local payment types.. SIX e-commerce solutions