PayPal e PHP

68
Confidential and Proprietary Verona 15 Maggio 2009 Giulio de Taddeo PayPal e PHP “…fare denaro è un’arte. Lavorare è un arte. Un buon affare è il massimo delle arti.”

description

Il pagamento è un momento critico che può fare la differenza tra un sito di successo ed uno che non genera abbastanza business. Attraverso vari strumenti PayPal offre la possibilità di poter gestire in tutta sicurezza gli incassi nel mondo online. In questo intervento verranno presentate le differenti modalità di integrazione dei prodotti PayPal illustrando i vari step (dalla sandbox al rilascio in produzione) necessari a creare rapidamente un’integrazione di successo.

Transcript of PayPal e PHP

Page 1: PayPal e PHP

Confidential and Proprietary

Verona 15 Maggio 2009

Giulio de Taddeo

PayPal e PHP

“…fare denaro è un’arte. Lavorare è un arte. Un buon affare è il massimo delle arti.”

Page 2: PayPal e PHP

Confidential and Proprietary

Perchè PayPal

Page 3: PayPal e PHP

Confidential and Proprietary 3

� Più di 184 milioni di conti registrati nel mondo

� Disponibile in 190 Paesi e territori e 17 valute

� $ 14 miliardi volume totale di pagamenti nel mondo nel 2007

� $ 563 milioni di ricavi nel 2007 (+35% YoY)

� Più di 184 milioni di conti registrati nel mondo

� Disponibile in 190 Paesi e territori e 17 valute

� $ 14 miliardi volume totale di pagamenti nel mondo nel 2007

� $ 563 milioni di ricavi nel 2007 (+35% YoY)

Diffusione di PayPal nel Mondo

Page 4: PayPal e PHP

Confidential and Proprietary 4

Con PayPal accetti pagamenti in 17 valute:

È inoltre possibile effettuare la conversione in altre 13 valute per le quali èdisponibile il DCC (Dynamic Currency Conversion) se l’acquirente ha una carta di credito operante in quella valuta.

Come Funziona PayPal

Page 5: PayPal e PHP

Confidential and Proprietary 5

Più valore con PayPal

Ricerca IPSOS (02/06)

61%

39%SOLO con

Principali motivi:� Sicurezza� Convenienza

Sales lift Survey ‘07

Il 36% non avrebbe effettuato l’acquisto in assenza di PayPal:

3 milioni di conti in Italia

Page 6: PayPal e PHP

Confidential and Proprietary 6

Perchè PayPal

Accettare PayPal vi permette di raggiungere unacommunity di acquirenti che altrimentiescludereste dal vostro business.

Acquirenti

Esercenti

Page 7: PayPal e PHP

Confidential and Proprietary 7

Page 8: PayPal e PHP

Confidential and Proprietary 8

Cosa significa Pagare con PayPal

Dal punto di vista dell’utente pagare con PayPal significa affrontare un flusso che incorporaalmeno due schermate (hostate da PayPal.com) che sono nei loro elementi principali invariantiovunque il buyer operi l’acquisto.

Page 9: PayPal e PHP

Confidential and Proprietary 9

Cosa significa Pagare con PayPal

Page 10: PayPal e PHP

Confidential and Proprietary 10

Cosa significa Pagare con PayPal

Page 11: PayPal e PHP

Confidential and Proprietary 11

Cosa significa Pagare con PayPal

Page 12: PayPal e PHP

Confidential and Proprietary 12

Perchè Pagare con PayPal

E’ anche utile tenere presente i principali driver d’uso di PayPal per la nostra community:– Sicurezza che i propri dati finanziari non vengono

condivisi con il venditore.– Esperienza d’acquisto facile e veloce.– Praticità.– Sicuro.

Page 13: PayPal e PHP

Confidential and Proprietary

Accettare PayPal

Page 14: PayPal e PHP

Confidential and Proprietary 14

Accettare Pagamenti sui Vostri Siti Internet

Esistono differenti soluzioni che permettono di accettare pagamenti su una piattaforma e-Commerce:

2. PayPal come metodo di Pagamento Aggiuntivo.

1. PayPal come unica soluzione per gestire tutti gli incassi generati dal vostro sito (Sole Solution).

Page 15: PayPal e PHP

Confidential and Proprietary

Prodotti PayPal

Page 16: PayPal e PHP

Confidential and Proprietary 16

Prodotti

In Italia sono disponibili due diversi prodotti integrabili sulle vostre piattaforme di e-Commerce:1. Express Checkout (Pagamento Express)

2. Website Payment Standard (Pagamento Standard)

Page 17: PayPal e PHP

Confidential and Proprietary

Integrare PayPal

Page 18: PayPal e PHP

Confidential and Proprietary 18

Prima di Cominciare

Per supportare e velocizzare il lavoro di integrazione PayPal mette a disposizione diversi tool:

• Sandbox (https://developer.paypal.com) – E’ un ambiente che permette di effettuare test di integrazione implementando pagamenti tra account fittizi.

• Integration Center (https://cms.paypal.com) – E’ il sito di supporto per gli sviluppatori.

• Centro Logo (https://www.paypal.com/it/logo) – E’ il punto in cui si possono trovare i loghi/bottoni PayPal necessari per completare l’integrazione.

• Blog Tecnico (http://developer.paypal-portal.com/pdn/board?board.id=it) – E’ il blog degli sviluppatori PayPal.

Page 19: PayPal e PHP

Confidential and Proprietary 19

PayPal SDK

Un ottimo facilitatore per le integrazioni sono gli SDK disponibili per gli sviluppatori.

Ovviamente sono disponibili diversi SDK in funzione della tecnologia già presente sulle proprie piattaforme oppure in funzione del linguaggio che meglio si conosce.

Percorso PayPal Developer Central -> Library -> SDKs

Page 20: PayPal e PHP

Confidential and Proprietary 20

Perchè il Layout è Importante

• Dare la giusta visibilità a PayPal sul vostro sito informa gli utenti PayPal che il loro metodo di pagamento preferito è accettato.

• PayPal consiglia di inserire il logo PayPal sulla HP, nella pagina di descrizione prodotto e nella pagina dedicata ai metodi di pagamento.

Page 21: PayPal e PHP

Confidential and Proprietary 21

Aumentare il Vostro Fatturato

Consentire agli utenti di pagare senza registrarsi sul vostro sito di e-Commerce.

E’ dimostrato che tanto più è rapido il flusso di pagamento (con meno schermate e form da riempire) quanto è piùpiacevole l’acquisto. Sussistono quindi maggiori probabilità che un visitatore occasionale diventi un cliente abituale.

Page 22: PayPal e PHP

Confidential and Proprietary 22

E’ fondamentale costruire un’esperienza d’acquisto fruibile e positiva!

Page 23: PayPal e PHP

Confidential and Proprietary 23

Iniziare l’Integrazione

Il primo passo a supporto di qualunque integrazione è la creazione di un account Sandbox in modo da poter testare il codice via via che verrà scritto.

Page 24: PayPal e PHP

Confidential and Proprietary 24

Iniziare l’Integrazione

Page 25: PayPal e PHP

Confidential and Proprietary 25

Iniziare l’Integrazione

Page 26: PayPal e PHP

Confidential and Proprietary 26

Iniziare l’Integrazione

Page 27: PayPal e PHP

Confidential and Proprietary

PayPal Website Payment Standard

Page 28: PayPal e PHP

Confidential and Proprietary 28

Website Payment Standard (WPS)

• Il prodotto WebsitePaymentStandard è un prodotto HTML based che ha nella semplicità di integrazione il suo atout principale.

• E’ un prodotto alla portata anche di chi non ha approfondite competenze di programmazione (facili wizard permettono la creazione automatica del codice relativo a pulsanti di pagamento).

• WPS permette di gestire agevolmente contenuti volumi transazionali.

Page 29: PayPal e PHP

Confidential and Proprietary 29

Website Payment Standard (WPS)

• Il flusso di pagamento è il seguente:

CC Provide Bill toand PayMethod

Information

OrderConfirmation

Add Item(s)to Shopping

Cart

Provide ShipTo

Information

Choose PayMethod

Visa, MC,PayPal

Review OrderSummary

PP

CC

Login toPayPal

TransactionConfirmation

Agree toTransaction

PP

• Dato che il pagamento avviene sui server di PayPal è necessario ottenere i dettagli dell’esito della transazione. Per tale motivo è necessario processare gli IPN.

Page 30: PayPal e PHP

Confidential and Proprietary 30

Instant Payment Notification – WPS

Gli IPN sono script (asincroni) e sono utili per aggiornare il vostro DB.

Per processare correttamente gli IPN è necessario costruire un listener che permetta di processare il messaggio:

1. Le URL di provenienza sono le seguenti (per evitare spoof):– URL di produzione: https://www.paypal.com/cgi-bin/webscr

– URL Sandbox: https://www.sandbox.paypal.com/cgi-bin/webscr

2. Parte del codice serve per recepire le variabili inviate dai server PayPal in modo da updatare il proprio DB.

3. E’ necessario convalidare la notifica ai server di PayPal: bisognapostare tutte le variabili (nel medesimo ordine) aggiungendo unavariabile cmd=_notify-validate.

4. PayPal restituisce una singola Word VERIFIED oppure INVALID a cui bisogna rispondere con un post 200 OK.

Page 31: PayPal e PHP

Confidential and Proprietary 31

Instant Payment Notification – WPS

5. Prima di processare l’ordine è consigliabile eseguire i seguenti test:– Payment_status sia Completed (gli IPN sono inviati anche

per transazioni in Pending o in altri stati)– Txn_id sia univoco (per prevenire frodi)– Receiver_email sia un proprio indirizzo valido– Se utilizzati verificare che i campo custom o Invoice siano

corretti

Page 32: PayPal e PHP

Confidential and Proprietary 32

Instant Payment Notification – WPS

E’ infine necessario definire l’indirizzo del listener IPN all’interno dell’account business PayPal (Account -> Profilo -> Preferenze per Notifica immediata del pagamento) oppure specificando l’indirizzo nella variabile notify_url.

Page 33: PayPal e PHP

Confidential and Proprietary 33

Instant Payment Notification – WPS// leggi il post del sistema PayPal e aggiungi cmd

$req = 'cmd=_notify-validate';

foreach ($_POST as $key => $value) {

$value = urlencode(stripslashes($value));

$req .= "&$key=$value";

}

// reinvia al sistema PayPal per la convalida

$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";

$header .= "Content-Type: application/x-www-form-urlencoded\r\n";

$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

// assegna variabili inviate a variabili locali

$item_name = $_POST['item_name'];

$item_number = $_POST['item_number'];

$payment_status = $_POST['payment_status'];

$payment_amount = $_POST['mc_gross'];

$payment_currency = $_POST['mc_currency'];

$txn_id = $_POST['txn_id'];$receiver_email = $_POST['receiver_email'];$payer_email = $_POST['payer_email'];

if (!$fp) {// HTTP ERROR

} else {fputs ($fp, $header . $req);while (!feof($fp)) {

$res = fgets ($fp, 1024);if (strcmp ($res, "VERIFIED") == 0) {

// check payment_status == Completed?// txn_id è già elaborato?// receiver_email è il tuo indirizzo?// payment_amount/payment_currency corretti?

// elabora pagamento}else if (strcmp ($res, "INVALID") == 0) {

// registra indagine manuale}

}fclose ($fp);}

Page 34: PayPal e PHP

Confidential and Proprietary 34

Payment Data Transfer – WPS

PDT è una comunicazione sincrona dipendente da azioni dell’utente.

PDT è un metodo per ottenere i dettagli della transazione in modo da costruire sul vostro sito una pagina riassuntiva del pagamento precedentemente avvenuto su PayPal.com

Dopo un pagamento PayPal trasmette la TransactionID ad un’indirizzo definito nel profilo dell’Account (Account -> Profilo -> Preferenze per i pagamenti su sito web).

Alla ricezione del TransactionID bisogna postare una FORM a PayPal che includa la TrasactionID ed il proprio Identity Token

<form method=post action="https://www.paypal.com/cgi-bin/webscr"><input type="hidden" name="cmd" value="_notify-synch"><input type="hidden" name="tx" value="TransactionID"><input type="hidden" name="at" value="YourIdentityToken"><input type="submit" value="PDT"></form>

SUCCESSfirst_name=Paolino+Paperinolast_name=De Paperipayment_status=Completedpayer_email=paperino%40hotmail.compayment_gross=5mc_currency=EURcustom=...

Page 35: PayPal e PHP

Confidential and Proprietary 35

Payment Data Transfer – WPS

Flusso di pagamento WPS + PDT

Page 36: PayPal e PHP

Confidential and Proprietary 36

Payment Data Transfer – WPS

Page 37: PayPal e PHP

Confidential and Proprietary 37

Payment Data Transfer – WPS

Page 38: PayPal e PHP

Confidential and Proprietary

PayPal Express Checkout

Page 39: PayPal e PHP

Confidential and Proprietary 39

Express Checkout

Express Checkout è un prodotto API based.

Express Checkout permette di adattare completamente il flusso di pagamento alle proprie esigenze.

Express Checkout permette di gestire in modo sincrono il flusso di pagamento.

Grazie alla DoExpressCheckoutPayment Express Checkout offre la possibilità di gestire l’incasso con una API call invece che tramite messaggistica asincrona.

Page 40: PayPal e PHP

Confidential and Proprietary 40

Express Checkout – API

Infrastruttura API di Express Checkout:

Page 41: PayPal e PHP

Confidential and Proprietary 41

Express Checkout – FlussiI flussi di pagamento principali sono i seguenti:

1. Express Checkout Mark– Adattamento del flusso di pagamento PayPal ad un

flusso di pagamento esistente. – Performante, ma si perde parte dei possibili benefici

che sarebbe possibile cogliere proponendo PayPal Express Checkout.

CC Provide Bill toand PayMethod

Information

OrderConfirmation

Add Item(s)to Shopping

Cart

Provide ShipTo

Information

Choose PayMethod

Visa, MC,PayPal

Review OrderSummary

Login toPayPal

TransactionConfirmation

PP

Page 42: PayPal e PHP

Confidential and Proprietary 42

Express Checkout – Flussi

2. Express Checkout Shortcut• Gli acquirenti possono acquistare anche senza

essersi preventivamente registrati presso il negozio (acquisto emozionale). La registrazione può essere proposta a valle del processo prefillando molti campi.

• Stessa infrastruttura di prodotto.

CC Provide Bill toand PayMethod

Information

OrderConfirmation

Add Item(s)to Shopping

Cart

Provide ShipTo

Information

Choose PayMethod

Visa, MC,PayPal

Review OrderSummary

Login toPayPal

TransactionConfirmation

PP PP

Page 43: PayPal e PHP

Confidential and Proprietary

SetExpressCheckout

Page 44: PayPal e PHP

Confidential and Proprietary 44

Express Checkout – SetExpressCheckout

Attraverso la SetEC è possibile ottenere il token necessario alla redirezione e settare alcuni parametri opzionali.

Page 45: PayPal e PHP

Confidential and Proprietary 45

Express Checkout – SetExpressCheckout

function PPHttpPost($methodName_, $nvpStr_) {//Prepara la req

$nvpreq="METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USE R=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

// Set the request as a POST FIELD for curl.curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

// Get response from the server.$httpResponse = curl_exec($ch);

if(!$httpResponse) {exit("$methodName_ failed:

".curl_error($ch).'('.curl_errno($ch).')');}

// Extract the response details.$httpResponseAr = explode("&", $httpResponse);

$httpParsedResponseAr = array();foreach ($httpResponseAr as $i => $value) {

$tmpAr = explode("=", $value);if(sizeof($tmpAr) > 1) {

$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];}

}return $httpParsedResponseAr;

}

// Set request-specific fields.$paymentAmount = urlencode('example_payment_amuont');$currencyID = urlencode(‘EUR');

$paymentType = urlencode('Sale');// or 'Sale' or 'Order' 'Authorization'

$returnURL = urlencode("return_url");$cancelURL = urlencode('cancel_url');

$nvpStr = "&Amt=$paymentAmount&ReturnUrl=$returnURL&CANCELURL=$cancelURL&PAYMENTACTION=$paymentType&CURRENCYCODE=$currencyID";

$httpParsedResponseAr = PPHttpPost('SetExpressCheckout', $nvpStr);

if("Success" == $httpParsedResponseAr["ACK"]) {// Redirect to paypal.com.$token = urldecode($httpParsedResponseAr["TOKEN"]);$payPalURL = "https://www.paypal.com/webscr&cmd=_express-

checkout&token=$token";if("sandbox" === $environment || "beta-sandbox" ===

$environment) {$payPalURL =

"https://www.$environment.paypal.com/webscr&cmd=_express-checkout&token=$token";

}header("Location: $payPalURL");exit;

} else {exit('SetExpressCheckout failed: ' .

print_r($httpParsedResponseAr, true));}

Page 46: PayPal e PHP

Confidential and Proprietary 46

function PPHttpPost($methodName_, $nvpStr_) {//Prepara la req

$nvpreq="METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USE R=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

// Set the request as a POST FIELD for curl.curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

// Get response from the server.$httpResponse = curl_exec($ch);

if(!$httpResponse) {exit("$methodName_ failed:

".curl_error($ch).'('.curl_errno($ch).')');}

// Extract the response details.$httpResponseAr = explode("&", $httpResponse);

$httpParsedResponseAr = array();foreach ($httpResponseAr as $i => $value) {

$tmpAr = explode("=", $value);if(sizeof($tmpAr) > 1) {

$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];}

}return $httpParsedResponseAr;

}

// Set request-specific fields.$paymentAmount = urlencode('example_payment_amuont');$currencyID = urlencode(‘EUR');

$paymentType = urlencode('Sale');// or 'Sale' or 'Order' 'Authorization'

$returnURL = urlencode("return_url");$cancelURL = urlencode('cancel_url');

$nvpStr = "&Amt=$paymentAmount&ReturnUrl=$returnURL&CANCELURL=$cancelURL&PAYMENTACTION=$paymentType&CURRENCYCODE=$currencyID";

$httpParsedResponseAr = PPHttpPost('SetExpressCheckout', $nvpStr);

if("Success" == $httpParsedResponseAr["ACK"]) {// Redirect to paypal.com.$token = urldecode($httpParsedResponseAr["TOKEN"]);$payPalURL = "https://www.paypal.com/webscr&cmd=_express-

checkout&token=$token";if("sandbox" === $environment || "beta-sandbox" ===

$environment) {$payPalURL =

"https://www.$environment.paypal.com/webscr&cmd=_express-checkout&token=$token";

}header("Location: $payPalURL");exit;

} else {exit('SetExpressCheckout failed: ' .

print_r($httpParsedResponseAr, true));}

Definizione delle credenziali

Le variabili obbligatorie da passare nella SetEC sono:VERSION = 57.0METHOD = SetExpressCheckoutRETURNURL = http://www.tuosito/pagina_di_ritorno.phpCANCELURL = http://www.tuosito/pagina_di_abbandono.phpAMT = 0.01

Express Checkout – SetExpressCheckout

Page 47: PayPal e PHP

Confidential and Proprietary 47

// Set request-specific fields.$paymentAmount = urlencode('example_payment_amuont');$currencyID = urlencode(‘EUR');

$paymentType = urlencode('Sale');// or 'Sale' or 'Order' 'Authorization'

$returnURL = urlencode("return_url");$cancelURL = urlencode('cancel_url');

$nvpStr = "&Amt=$paymentAmount&ReturnUrl=$returnURL&CANCELURL=$cancelURL&PAYMENTACTION=$paymentType&CURRENCYCODE=$currencyID";

$httpParsedResponseAr = PPHttpPost('SetExpressCheckout', $nvpStr);

if("Success" == $httpParsedResponseAr["ACK"]) {// Redirect to paypal.com.$token = urldecode($httpParsedResponseAr["TOKEN"]);$payPalURL = "https://www.paypal.com/webscr&cmd=_express-

checkout&token=$token";if("sandbox" === $environment || "beta-sandbox" ===

$environment) {$payPalURL =

"https://www.$environment.paypal.com/webscr&cmd=_express-checkout&token=$token";

}header("Location: $payPalURL");exit;

} else {exit('SetExpressCheckout failed: ' .

print_r($httpParsedResponseAr, true));}

function PPHttpPost($methodName_, $nvpStr_) {//Prepara la req

$nvpreq="METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USE R=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

// Set the request as a POST FIELD for curl.curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

// Get response from the server.$httpResponse = curl_exec($ch);

if(!$httpResponse) {exit("$methodName_ failed:

".curl_error($ch).'('.curl_errno($ch).')');}

// Extract the response details.$httpResponseAr = explode("&", $httpResponse);

$httpParsedResponseAr = array();foreach ($httpResponseAr as $i => $value) {

$tmpAr = explode("=", $value);if(sizeof($tmpAr) > 1) {

$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];}

}return $httpParsedResponseAr;

}

Definizione dei parametri di pagamento e del tipo di pagamento (contestuale o order+auth+capt)

Express Checkout – SetExpressCheckout

Page 48: PayPal e PHP

Confidential and Proprietary 48

function PPHttpPost($methodName_, $nvpStr_) {//Prepara la req

$nvpreq="METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USE R=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

// Set the request as a POST FIELD for curl.curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);

// Get response from the server.$httpResponse = curl_exec($ch);

if(!$httpResponse) {exit("$methodName_ failed:

".curl_error($ch).'('.curl_errno($ch).')');}

// Extract the response details.$httpResponseAr = explode("&", $httpResponse);

$httpParsedResponseAr = array();foreach ($httpResponseAr as $i => $value) {

$tmpAr = explode("=", $value);if(sizeof($tmpAr) > 1) {

$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];}

}return $httpParsedResponseAr;

}

// Set request-specific fields.$paymentAmount = urlencode('example_payment_amuont');$currencyID = urlencode(‘EUR');

$paymentType = urlencode('Sale');// or 'Sale' or 'Order' 'Authorization'

$returnURL = urlencode("return_url");$cancelURL = urlencode('cancel_url');

$nvpStr = "&Amt=$paymentAmount&ReturnUrl=$returnURL&CANCELURL=$cancelURL&PAYMENTACTION=$paymentType&CURRENCYCODE=$currencyID";

$httpParsedResponseAr = PPHttpPost('SetExpressCheckout', $nvpStr);

if("Success" == $httpParsedResponseAr["ACK"]) {// Redirect to paypal.com.$token = urldecode($httpParsedResponseAr["TOKEN"]);$payPalURL = "https://www.paypal.com/webscr&cmd=_express-

checkout&token=$token";if("sandbox" === $environment || "beta-sandbox" ===

$environment) {$payPalURL =

"https://www.$environment.paypal.com/webscr&cmd=_express-checkout&token=$token";

}header("Location: $payPalURL");exit;

} else {exit('SetExpressCheckout failed: ' .

print_r($httpParsedResponseAr, true));}

Gestione del token

Redirezione

Express Checkout – SetExpressCheckout

Page 49: PayPal e PHP

Confidential and Proprietary 49

Express Checkout – SetExpressCheckout

E’ possibile customizzare alcuni elementi delle pagine di Checkouthostate da PayPal.com

E’ buona norma per esempio utilizzare un logo nella pagina di pagamento (è consigliabile che sia hostato su server https).

Se la piattaforma di e-Commerce ha già provveduto a raccogliere l’indirizzo di spedizione è importante operare l’override dell’indirizzo dell’utente (ADDRESSOVERRIDE=1).

...&METHOD=SetExpressCheckout &RETURNURL=https://... &CANCELURL=https://... &AMT=10.00&CURRENCYCODE=EUR &PAYMENTACTION=Sale& &HDRIMG=https://www.test.it/website-logo.gifADDRESSOVERRIDE=1&SHIPTOSTREET=Via vai 1 SHIPTOSTREET2= &SHIPTOCITY=Milano&SHIPTOSTATE=MI&SHIPTOCOUNTRYCODE=IT &SHIPTOZIP=20124&PHONENUM=02-22222222...

Page 50: PayPal e PHP

Confidential and Proprietary 50

Express Checkout – SetExpressCheckout

Usualmente per facilitare i processi contabili di quadratura si utilizza la variabile invnum che permette di accoppiare alla transazione un proprio univoco (codice fattura).

Laddove si stia vendendo un bene/servizio digitale èconsigliabile oscurare la sezione relativa all’indirizzo di spedizione con il parametro noshipping=1

In una piattaforma di e-Commerce multilingua ènecessario utilizzare la variabile localecode per impostare la lingua nelle pagine di pagamento hostate su PayPal.com

Page 51: PayPal e PHP

Confidential and Proprietary 51

Express Checkout – Sole Solution

E’ possibile anche con Express Checkout avvalersi della possibilità di accettare anche pagamenti provenienti da carte di credito.

Per abilitare tale servizio si utilizzano i parametri:

landingpage=billing e solutiontype=sole.

Nel caso la vostra piattaforma utilizzi già un gateway bancario per l’addebito delle carte di credito si può forzare da codice la possibilità di accettare solo pagamenti provenienti da account PayPal.

In tal caso si useranno i seguenti settaggi:

landingpage=login e solutiontype=mark

Page 52: PayPal e PHP

Confidential and Proprietary

GetExpressCheckoutDetails

Page 53: PayPal e PHP

Confidential and Proprietary 53

Express Checkout – GetExpressCheckoutDetails

GetECDetails è una chiamata opzionale.

Permette di retrivare dettagli dell’account che sta per completare l’acquisto.

GetECDetails diventa una chiamata obbligatoria quando si sta implementando un flusso di pagamento che prevede la vendita anche ad utenti non registrati.

Page 54: PayPal e PHP

Confidential and Proprietary 54

Express Checkout – GetExpressCheckoutDetails

// Obtain the token from PayPal.if(!array_key_exists('token', $_REQUEST)) {

exit('Token is not received.');}

$token = urlencode(htmlspecialchars($_REQUEST['token']));$nvpStr = "&TOKEN=$token";

// Chiamata API GetEC$httpParsedResponseAr = PPHttpPost('GetExpressCheckoutDetails', $nvpStr);

if("Success" == $httpParsedResponseAr["ACK"]) {// Extract the response details.$payerID = $httpParsedResponseAr['PAYERID'];$street1 = $httpParsedResponseAr["SHIPTOSTREET"];if(array_key_exists("SHIPTOSTREET2",

$httpParsedResponseAr)) {$street2 =

$httpParsedResponseAr["SHIPTOSTREET2"];}$city_name = $httpParsedResponseAr["SHIPTOCITY"];$state_province = $httpParsedResponseAr["SHIPTOSTATE"];$postal_code = $httpParsedResponseAr["SHIPTOZIP"];$country_code =

$httpParsedResponseAr["SHIPTOCOUNTRYCODE"];

exit('Get Express Checkout Details Completed Successfully: '.print_r($httpParsedResponseAr, true));} else {

exit('GetExpressCheckoutDetails failed: ' . print_r($httpParsedResponseAr, true));}

function PPHttpPost($methodName_, $nvpStr_) {...$nvpreq =

"METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

// Set the request as a POST FIELD for curl.curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);// Get response from the server.$httpResponse = curl_exec($ch);if(!$httpResponse) {

exit('$methodName_ failed: '.curl_error($ch).'('.curl_errno($ch).')');

}

// Extract the response details.$httpResponseAr = explode("&", $httpResponse);

$httpParsedResponseAr = array();foreach ($httpResponseAr as $i => $value) {

$tmpAr = explode("=", $value);if(sizeof($tmpAr) > 1) {

$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];}

}

if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {

exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");

}

return $httpParsedResponseAr;}

Page 55: PayPal e PHP

Confidential and Proprietary 55

Express Checkout – GetExpressCheckoutDetails

// Obtain the token from PayPal.if(!array_key_exists('token', $_REQUEST)) {

exit('Token is not received.');}

$token = urlencode(htmlspecialchars($_REQUEST['token']));$nvpStr = "&TOKEN=$token";

// Chiamata API GetEC$httpParsedResponseAr = PPHttpPost('GetExpressCheckoutDetails', $nvpStr);

if("Success" == $httpParsedResponseAr["ACK"]) {// Extract the response details.$payerID = $httpParsedResponseAr['PAYERID'];$street1 = $httpParsedResponseAr["SHIPTOSTREET"];if(array_key_exists("SHIPTOSTREET2",

$httpParsedResponseAr)) {$street2 =

$httpParsedResponseAr["SHIPTOSTREET2"];}$city_name = $httpParsedResponseAr["SHIPTOCITY"];$state_province = $httpParsedResponseAr["SHIPTOSTATE"];$postal_code = $httpParsedResponseAr["SHIPTOZIP"];$country_code =

$httpParsedResponseAr["SHIPTOCOUNTRYCODE"];

exit('Get Express Checkout Details Completed Successfully: '.print_r($httpParsedResponseAr, true));} else {

exit('GetExpressCheckoutDetails failed: ' . print_r($httpParsedResponseAr, true));}

function PPHttpPost($methodName_, $nvpStr_) {...$nvpreq =

"METHOD=$methodName_&VERSION=$version&PWD=$API_Password&USER=$API_UserName&SIGNATURE=$API_Signature$nvpStr_";

// Set the request as a POST FIELD for curl.curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);// Get response from the server.$httpResponse = curl_exec($ch);if(!$httpResponse) {

exit('$methodName_ failed: '.curl_error($ch).'('.curl_errno($ch).')');

}

// Extract the response details.$httpResponseAr = explode("&", $httpResponse);

$httpParsedResponseAr = array();foreach ($httpResponseAr as $i => $value) {

$tmpAr = explode("=", $value);if(sizeof($tmpAr) > 1) {

$httpParsedResponseAr[$tmpAr[0]] = $tmpAr[1];}

}

if((0 == sizeof($httpParsedResponseAr)) || !array_key_exists('ACK', $httpParsedResponseAr)) {

exit("Invalid HTTP Response for POST request($nvpreq) to $API_Endpoint.");

}

return $httpParsedResponseAr;}

Raccolta dei dettagli dell’acquirente

Page 56: PayPal e PHP

Confidential and Proprietary

DoExpressCheckoutPayment

Page 57: PayPal e PHP

Confidential and Proprietary 57

Express Checkout – DoExpressCheckoutPayment

DoECPayament è la chiamata cardine di ExpressCheckout perchè è la funzione che da’ luogo se successful all’incasso vero e proprio (se PAYMENTACTION=Sale).

$payerID = urlencode("payer_id");$token = urlencode("token");

$paymentType = urlencode("Authorization");// or 'Sale' or 'Order'

$paymentAmount = urlencode("payment_amount");$currencyID = urlencode(“EUR");

$nvpStr = "&TOKEN=$token&PAYERID=$payerID&PAYMENTACTION=$paymentType&AMT=$paymentAmount&CURRENCYCODE=$currencyID";

// API call$httpParsedResponseAr = PPHttpPost('DoExpressCheckoutPayment', $nvpStr);

if("Success" == $httpParsedResponseAr["ACK"]) {exit('Express Checkout Payment Completed Successfully:

'.print_r($httpParsedResponseAr, true));} else {

exit('DoExpressCheckoutPayment failed: ' . print_r($httpParsedResponseAr, true));}

Parametri principali

Page 58: PayPal e PHP

Confidential and Proprietary

Express Checkout Shortcut

Page 59: PayPal e PHP

Confidential and Proprietary 59

Express Checkout Shortcut

Per poter ridurre il flusso di pagamento al massimo è buona norma operare quanto segue:

• Valorizzare nella SetEC almeno il campo descinviando il dettaglio del Totale da addebitare.

• Accodare all’URL insieme al token useraction=commit (non passarla come variabile nella stringa NVP)

In tal modo il vostro acquirente nella seconda pagina del pagamento avrà visione del totale da pagare e avrà la percezione di essere addebitato a seguito del click sul bottone Paga Ora.

Page 60: PayPal e PHP

Confidential and Proprietary 60

Express Checkout Shortcut

Page 61: PayPal e PHP

Confidential and Proprietary

Order Authorization & Capture

Page 62: PayPal e PHP

Confidential and Proprietary 62

Order – Authorization – Capture

Oltre a pagamenti contestuali è possibile fruire di una modalità di pagamento che prevede 3 distinte fasi:

1. Order2. Authorization – Allocazione di fondi da plafond.3. Capture – Cattura dei fondi precedentemente

riservati.

Page 63: PayPal e PHP

Confidential and Proprietary 63

Express Checkout – Order

Una chiamata order successful apre una finestra temporale di 29 giorni all’interno della quale èpossibile effettuare successive autorizzazioni.

Per poter implementare un order è sufficiente impostare il seguente parametro paymentaction=order nella DoExpressCheckout

Page 64: PayPal e PHP

Confidential and Proprietary 64

Express Checkout – DoAuthorization

Se la vostra piattaforma di e-Commerce ha effettuato con successo un order è possibile invocare un’autorizzazione con l’API DoAuthorization.

L’autorizzazione provvede a verificare la disponibilità dei fondi richiesti e se possibile ne richiede il blocco.

TransactionID ritornato dalla DoEC diventa l’AuthorizationID

$transactionID = urlencode('example_transaction_id');$amount = urlencode('example_amount');$currency = urlencode(‘EUR');

$nvpStr="&TRANSACTIONID=$transactionID&AMT=$amount&CURRENCYCODE=$currency";

// Execute the API$httpParsedResponseAr = PPHttpPost('DoAuthorization', $nvpStr);

if("Success" == $httpParsedResponseAr["ACK"]) {exit('DoAuthorization Completed Successfully:

'.print_r($httpParsedResponseAr, true));} else {

exit('DoAuthorization failed: ' . print_r($httpParsedResponseAr, true));}

Page 65: PayPal e PHP

Confidential and Proprietary 65

Express Checkout – DoCaptureOrder

Se una chiamata DoAuthorization ha avuto successo si apre una finestra temporale di 3 giorni* per poter effettuare una chiamata DoCapture.

*Valore standard

$authorizationID = urlencode('example_authorization_id');$amount = urlencode('example_amount');$currency = urlencode(‘EUR');

$completeCodeType = urlencode('Complete');

$invoiceID = urlencode('example_invoice_id');

$nvpStr="&AUTHORIZATIONID=$authorizationID&AMT=$amount&COMPLETETYPE=$completeCodeType&CURRENCYCODE=$currency";

// Execute the API operation;$httpParsedResponseAr = PPHttpPost('DoCapture', $nvpStr);

if("Success" == $httpParsedResponseAr["ACK"]) {exit('Capture Completed Successfully:

'.print_r($httpParsedResponseAr, true));} else {

exit('DoCapture failed: ' . print_r($httpParsedResponseAr, true));}

CompleteType=Complete indica che il Capture invocato è l’ultimo

Page 66: PayPal e PHP

Confidential and Proprietary 66

Express Checkout – DoVoid

Se per qualche motivo di business non si intende chiudere le chiamate, è necessario utilizzare la chiamata DoVoid per effettuare l’annullamento della precedente operazione di Authorization.

*Valore standard

$authorizationID = urlencode('authorization_id');

$nvpStr="&AUTHORIZATIONID=$authorizationID";

// Execute the API$httpParsedResponseAr = PPHttpPost('DOVoid', $nvpStr);

if("Success" == $httpParsedResponseAr["ACK"]) {exit('Void Completed Successfully:

'.print_r($httpParsedResponseAr, true));} else {

exit('DoVoid failed: ' . print_r($httpParsedResponseAr, true));}

Page 67: PayPal e PHP

Confidential and Proprietary 67

THANK YOU FOR YOUR TIMEDomande?

Page 68: PayPal e PHP

Confidential and Proprietary

Verona 15 Maggio 2009

Giulio de Taddeo

PayPal e PHP

“…fare denaro è un’arte. Lavorare è un arte. Un buon affare è il massimo delle arti.”