1. Preparation before development
https://developer.paypal.com/ Go to the official developer website of paypal to register a developer account.
After logging in with your account, click dashboard on the navigation to enter the dashboard. As shown in the screenshot below, subsequent operations are performed in this panel.
You can see the buyer account and seller account of your sandbox test in Accounts under the menu Sandbox in the screenshot above. Both test accounts have a profile option with changepassword to set the password for the virtual account.
Transactions under the menu Sandbox in the screenshot above is your transaction record.
Click the Create App button in the upper right corner of the screenshot page. Create an app. After creation, you will be provided with a Client ID and Secret. These two can be configured as PHP constants and will be used in later development.
2. Enter payment demo development
Create a development code root directory locally. First create an index.html and put two simple input items: product name and product price. The code and screenshots are as follows:
<ol class="dp-c"> <li class="alt"><span><span>DOCTYPE html> </span></span></li> <li><span><html lang=<span class="string">"en"</span><span>> </span></li> <li class="alt"><span> <head> </span></li> <li><span> <meta charset=<span class="string">"utf-8"</span><span>> </span></li> <li class="alt"><span> <title>支付页面title> </span></li> <li><span> head> </span></li> <li class="alt"><span> <body> </span></li> <li><span> <div> </span></li> <li class="alt"><span> <form action=<span class="string">"checkout.php"</span><span> method=</span><span class="string">"post"</span><span> autocomplete=</span><span class="string">"off"</span><span>> </span></li> <li><span> <label <span class="keyword">for</span><span>=</span><span class="string">"item"</span><span>> </span></li> <li class="alt"><span> 产品名称 </span></li> <li><span> <input type=<span class="string">"text"</span><span> name=</span><span class="string">"product"</span><span>> </span></li> <li class="alt"><span> label> </span></li> <li><span> <br> </span></li> <li class="alt"><span> <label <span class="keyword">for</span><span>=</span><span class="string">"amount"</span><span>> </span></li> <li><span> 价格 </span></li> <li class="alt"><span> <input type=<span class="string">"text"</span><span> name=</span><span class="string">"price"</span><span>> </span></li> <li><span> label> </span></li> <li class="alt"><span> <br> </span></li> <li><span> <input type=<span class="string">"submit"</span><span> value=</span><span class="string">"去付款"</span><span>> </span></li> <li class="alt"><span> form> </span></li> <li><span> div> </span></li> <li class="alt"><span> body> </span></li> <li><span>html> </span></li> </ol>
Enter product name and price. Click to pay and you will go to the paypal payment page. Use your sandbox test buyer account to pay. You will find that the payment is successful. Then log in to your test seller account. You will find that the seller's account has received payment. Of course, the handling fee charged by Paypal will be deducted here. The handling fee is charged by the seller.
Let’s take a closer look at how php is implemented. First, you need to get the php-sdk provided by paypal into your code directory. Here we introduce how to use PHP's package manager composer to obtain the latest SDK. Of course, you can obtain the latest paypal PHP-SDK from other channels such as github.
Composer is already installed on your computer by default. If you don’t have it, go to Du Niang or google to install it with composer.
Then write a composer.json file in your code root directory to get the package content. The json file code is as follows:
{
"require" : { "paypal/rest-api-sdk-php" : "1.5.1"
}
}
If this is a linux/unix system, just execute composer install directly in the root directory to obtain the package content.
After installation. A vendor directory will be generated under the root directory. There are two subdirectories: composer and paypal. Composer implements automatic loading, and paypal is your sdk content.
Next, let’s write a public file (app/start.php is used by default, you can customize it in your project). In fact, it just implements the automatic loading of sdk’s autoload.php and creates the client id just mentioned above. and the paypal payment object instance generated by secret. The start.php code is as follows:
phprequire "vendor/autoload.php"; //Load the sdk's autoload file define('SITE_URL' , 'http://www.paydemo.com'); //Self-defined website url//Create payment object instance $paypal = new PayPalRestApiContext( new PayPalAuthOAuthTokenCredential( 'Your Client ID' 'Your secret'
)
);
The next step is to implement the processing file checkout.php submitted in the form. The code content is as follows:
php/**
* @author xxxxxxxx
* @brief 简介:
* @date 15/9/2
* @time 下午5:00
*/
use PayPalApiPayer;
use PayPalApiItem;
use PayPalApiItemList;
use PayPalApiDetails;
use PayPalApiAmount;
use PayPalApiTransaction;
use PayPalApiRedirectUrls;
use PayPalApiPayment;
use PayPalExceptionPayPalConnectionException;
require "app/start.php"; if (!isset($_POST['product'], $_POST['price'])) { die("lose some params"); }$product = $_POST['product']; $price = $_POST['price']; $shipping = 2.00; //运费 $total = $price $shipping; $payer = new Payer(); $payer->setPaymentMethod('paypal'); $item = new Item(); $item->setName($product) ->setCurrency('USD') ->setQuantity(1) ->setPrice($price); $itemList = new ItemList(); $itemList->setItems([$item]); $details = new Details(); $details->setShipping($shipping) ->setSubtotal($price); $amount = new Amount(); $amount->setCurrency('USD') ->setTotal($total) ->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount) ->setItemList($itemList) ->setDescription("支付描述内容") ->setInvoiceNumber(uniqid()); $redirectUrls= new RedirectUrls(); $redirectUrls->setReturnUrl(SITE_URL . '/pay.php?success=true') ->setCancelUrl(SITE_URL . '/pay.php?success=false'); $payment = new Payment(); $payment->setIntent('sale') ->setPayer($payer) ->setRedirectUrls($redirectUrls) ->setTransactions([$transaction]); try { $payment->create($paypal); } catch (PayPalConnectionException $e) { echo $e->getData(); die(); } $approvalUrl = $payment->getApprovalLink(); header("Location: {$approvalUrl}");
checkout.php initializes and sets the specific payment details and parameters through the parameters submitted through the form. Only the commonly used parts are listed here. PayPal provides many parameter settings. For more details, you can refer to Paypal's official developer documentation.
After checkout.php sets the parameters. A payment link will be generated. Use the header to jump to the payment link (which is the payment page of Paypal). When you go to the payment page, you can use the buyer account provided by your sandbox to pay. The screenshot is as follows:
After the payment is completed using the buyer account. Go check the merchant account balance of your sandbox. You will find that you have received the money minus the handling fee.
There is a callback processing after the payment is successful or failed. The php file for callback processing is set at setReturnUrl in checkout.php above. What is set here is /pay.php?success=true
Next let’s take a look at how pay.php simply handles callbacks. First paste the pay.php code:
php
require 'app/start.php';
use PayPalApiPayment;
use PayPalApiPaymentExecution;
if(!isset($_GET['success'], $_GET['paymentId'], $_GET['PayerID'])){
die();
}
if((bool)$_GET['success']=== 'false'){
echo 'Transaction cancelled!';
die();
}
$paymentID = $_GET['paymentId'];
$payerId = $_GET['PayerID'];
$payment = Payment::get($paymentID, $paypal);
$execute = new PaymentExecution();
$execute->setPayerId($payerId);
try{
$result = $payment->execute($execute, $paypal);
}catch(Exception $e){
die($e);
}
echo '支付成功!感谢支持!';
好了。到这里一个简单的paypal支付的demo其实已经走通了。懂得支付原理之后、想要再你自己的项目里面进行更丰富的扩展、就去paypal的官方文档查看更多具体的开发项设置。包括交易明细的获取等等都是可以实现的。这里就不具体讲下去了。