PayPal sdk v1版本php开发支付过程
生活随笔
收集整理的這篇文章主要介紹了
PayPal sdk v1版本php开发支付过程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
首先PayPal官網下載PHP版SDK程序
通過php composer下載sdk:
composer require paypal/rest-api-sdk-php
或github下載:
git clone https://github.com/paypal/PayPal-PHP-SDK.git
PayPal入口程序
bootstrap.php
<?php require 'autoload.php'; require 'common.php';use PayPal\Auth\OAuthTokenCredential; use PayPal\Rest\ApiContext;// Suppress DateTime warnings, if not set already //date_default_timezone_set(@date_default_timezone_get()); // Adding Error Reporting for understanding errors properly error_reporting(0); ini_set('display_errors', '1'); //引入支付配置文件 require ROOT . 'config/api/pay/pay.php'; // Replace these values by entering your own ClientId and Secret by visiting https://developer.paypal.com/developer/applications///配置參數 if ($_REQUEST['uid'] == 664590) {//某個用戶測試sandbox//sandbox測試配置$clientId = TEST_PAYPAL_CLIENT_ID;$clientSecret = TEST_PAYPAL_CLIENT_SECRET;$mode = 'sandbox'; } else {//live正式配置$clientId = PAYPAL_CLIENT_ID;$clientSecret = PAYPAL_CLIENT_SECRET;$mode = 'live'; }$apiContext = getApiContext($clientId, $clientSecret, $mode); return $apiContext;/*** @param $clientId* @param $clientSecret* @param $mode //模式,sandbox或live* @return ApiContext*/ function getApiContext($clientId, $clientSecret, $mode) {$apiContext = new ApiContext(new OAuthTokenCredential($clientId,$clientSecret));$apiContext->setConfig(array('mode' => $mode,'cache.enabled' => true,));return $apiContext; }pay.php
<?php// # Create Billing Agreement with PayPal as Payment Source // // This sample code demonstrate how you can create a billing agreement, as documented here at: // https://developer.paypal.com/webapps/developer/docs/api/#create-an-agreement // API used: /v1/payments/billing-agreements// Retrieving the Plan from the Create Update Sample. This would be used to // define Plan information to create an agreement. Make sure the plan you are using is in active state. /** @var Plan $createdPlan */ require 'bootstrap.php';use PayPal\Api\Amount; use PayPal\Api\Details; use PayPal\Api\Item; use PayPal\Api\ItemList; use PayPal\Api\Payer; use PayPal\Api\Payment; use PayPal\Api\RedirectUrls; use PayPal\Api\Transaction;$ordernum = $_REQUEST['ordernum'] ?? '';//自定義參數 $custom = json_encode(['infoid' => $_REQUEST['infoid'],'ordernum' => $ordernum,'paidtime' => $_SERVER['REQUEST_TIME'],'returnUrl' => $retUrl, ]);$amount = new Amount(); $amount->setCurrency("CAD")->setTotal($_REQUEST['payprice']);$transaction = new Transaction(); $transaction->setAmount($amount)->setDescription($_REQUEST['desc'])->setCustom($custom)->setInvoiceNumber(uniqid()); $baseUrl = getBaseUrl();$redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl($baseUrl . '/ExecutePayment.php?success=true&paytype=paypal&ordernum=' . $ordernum . '&infoid=' . $_REQUEST['infoid'])->setCancelUrl($baseUrl . '/ExecutePayment.php?success=false&paytype=paypal&ordernum=' . $ordernum . '&infoid=' . $_REQUEST['infoid']);$payer = new Payer(); $payer->setPaymentMethod("paypal");$payment = new Payment(); $payment->setIntent("sale")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); $request = clone $payment; try {$payment->create($apiContext); } catch (Exception $ex) {ResultPrinter::printError("Created Payment Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex);exit(1); } $approvalUrl = $payment->getApprovalLink(); header('Location:' . $approvalUrl);支付回調程序
ExecutePayment.php
<?php // #Execute Agreement // This is the second part of CreateAgreement Sample. // Use this call to execute an agreement after the buyer approves itrequire 'bootstrap.php';// ## Approval Status use PayPal\Api\ExecutePayment; use PayPal\Api\Payment; use PayPal\Api\PaymentExecution;// echo '<script>var FROM = "' . ($_GET['os'] ? 'app' : '') . '; var OS = "' . $_GET['os'] . '";</script>'; // Determine if the user accepted or denied the request $infoid = (int)($_GET['infoid'] ?? 0); $paymentId = Mstr()->encode($_GET['paymentId'] ?? ''); $ordernum = Mstr()->encode($_GET['ordernum'] ?? ''); if (isset($_GET['success']) && $_GET['success'] == 'true') {try {$payment = Payment::get($paymentId, $apiContext);$execution = new PaymentExecution();$execution->setPayerId(Mstr()->encode($_GET['PayerID'] ?? ''));$result = $payment->execute($execution, $apiContext); //這里如果支付失敗,或異常則會拋出異常throw Exception,下面語句不會執行//記錄支付成功狀態程序echo "<script>goto('" . $returnUrl . "', 1, 1);</script>";} catch (Exception $ex) {echo "<script>goto('" . $returnUrl . "', 1, 1);</script>";} }webhook 簽名驗證和確認訂單支付成功,修改訂單狀態
webhooks.php
<?php //webhook 確認訂單支付成功,修改訂單狀態$headers = getallheaders(); $headers = array_change_key_case($headers, CASE_UPPER); $body = file_get_contents('php://input'); $returnData = json_decode($body, true);// 創建了webhook在PayPal開發者后臺查找webhookId $webhookId = '5BM77961TW281551X'; // 簽名字符串 $signData = $headers['PAYPAL-TRANSMISSION-ID'] . '|' . $headers['PAYPAL-TRANSMISSION-TIME'] . '|' . $webhookId . '|' . crc32($body);// 加載證書并提取公鑰 $pubKey = openssl_pkey_get_public(file_get_contents($headers['PAYPAL-CERT-URL'])); $key = openssl_pkey_get_details($pubKey)['key'];$signature = base64_decode($headers['PAYPAL-TRANSMISSION-SIG']); //根據提供的簽名驗證數據 $verifyResult = openssl_verify($signData,$signature,$key,'sha256WithRSAEncryption' );//簽名驗證成功 if ($verifyResult == 1) {//訂單支付完成if ($returnData['event_type'] == 'PAYMENT.SALE.COMPLETED') {$ordernum = $returnData['resource']['invoice_number'];//由于webhook不能file_put_contents寫入文件,將調試日志記錄在數據庫M('c')->insert('test_paypal', ['content' => json_encode($returnData),'log' => 'sigData:' . $signData . ' ++++ verifyResult:' . $verifyResult . ' ++++ key:' . $key . ' ++++ orderNo:' . $ordernum . ' ++++ headers:' . json_encode($headers),]);//以下是支付成功修改訂單狀態程序}else {return 'Not Completed';} } else {return 'sign error';//簽名驗證失敗 或請求錯誤 } return 'success';退款
function returnMoney() {try {$txn_id = "xxxxxxx"; //異步加調中拿到的id$amt = new Amount();$amt->setCurrency('USD')->setTotal('99'); // 退款的費用$refund = new Refund();$refund->setAmount($amt);$sale = new Sale();$sale->setId($txn_id);$refundedSale = $sale->refund($refund, $this->PayPal);} catch (\Exception $e) {// PayPal無效退款return json_decode(json_encode(['message' => $e->getMessage(), 'code' => $e->getCode(), 'state' => $e->getMessage()])); // to object}// 退款完成return $refundedSale; }總結
以上是生活随笔為你收集整理的PayPal sdk v1版本php开发支付过程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 竞赛经验分享 NUIST CEEE慕课
- 下一篇: php计算用户实际付的金额,复盘微信支付