要在PHP中使用PayPal支付接口,您需要遵循以下步驟:
創建PayPal商家賬戶:首先,您需要注冊一個PayPal商家賬戶。訪問https://www.paypal.com/,然后點擊“商家工具”并注冊。
獲取API憑據:登錄到您的PayPal商家賬戶,然后轉到“我的業務設置”>“API安全”>“API憑據”。在這里,您將看到您的API用戶名、密碼和簽名。復制這些值,因為您將在PHP代碼中使用它們。
下載PayPal PHP SDK:訪問https://github.com/paypal/PayPal-PHP-SDK,然后下載或克隆存儲庫。將其解壓縮到您的項目文件夾中。
配置autoload.php:在您的PHP文件中,包含PayPal SDK的autoload.php文件。例如:
require 'path/to/PayPal-PHP-SDK/autoload.php';
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
$api_username = "your_api_username";
$api_password = "your_api_password";
$api_signature = "your_api_signature";
$credentials = new OAuthTokenCredential($api_username, $api_password, $api_signature);
$apiContext = new ApiContext($credentials);
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
$payer = new Payer();
$payer->setPaymentMethod("paypal");
$item1 = new Item();
$item1->setName('Item 1')
->setCurrency('USD')
->setQuantity(1)
->setPrice(7.5);
$itemList = new ItemList();
$itemList->setItems(array($item1));
$details = new Details();
$details->setShipping(1.2)
->setTax(1.3)
->setSubtotal(7.50);
$amount = new Amount();
$amount->setCurrency("USD")
->setTotal(10)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("http://yourdomain.com/return")
->setCancelUrl("http://yourdomain.com/cancel");
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction));
try {
$payment->create($apiContext);
} catch (Exception $ex) {
echo $ex;
exit(1);
}
$approvalUrl = $payment->getApprovalLink();
header("Location: " . $approvalUrl);
// return.php
$paymentId = $_GET['paymentId'];
$payment = Payment::get($paymentId, $apiContext);
$execution = new PaymentExecution();
$execution->setPayerId($_GET['PayerID']);
try {
$result = $payment->execute($execution, $apiContext);
// Payment is successful, update your database and display a success message
} catch (Exception $ex) {
// Payment failed, display an error message
}
// cancel.php
// Display a cancellation message
現在,您已經成功地在PHP中設置了PayPal支付接口。用戶可以通過PayPal進行支付,您可以處理支付確認和取消。