项目需要使用到PayPal支付,在网上找了一圈大多写的太过简陋不易看懂,在这里详细记录集成过程方便后期使用.
第一步:下载PayPal-PHP-SDK集成到项目中
最新SDK下载地址: https://github.com/paypal/PayPal-PHP-SDK/releases
官方英文文档:点击打开链接
下载sdk解压,我们需要使用到路径:PayPal-PHP-SDK-1.13.0\PayPal-PHP-SDK\paypal\rest-api-sdk-php\lib下的文件夹
如图:
将文件夹导入到tp5项目的extend目录下:
同时也需要将压缩包中log记录的Psr文件夹导入,否则运行会报错
第二步:项目中的使用
step1: 配置ApiContext,也就是设置PayPal官网申请的clientId和clientSecret,具体申请方法很多教程有,这里不写
$apiContext = new ApiContext(new OAuthTokenCredential(config('paypal')['clientId'], // paypal 官网获取的clientId和clientSecretconfig('paypal')['clientSecret']));$apiContext->setConfig(array(// 'mode' => 'sandbox','mode' => 'live','log.LogEnabled' => false,'log.FileName' => '../PayPal.log','log.LogLevel' => 'Info', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS'cache.enabled' => true,'http.CURLOPT_CONNECTTIMEOUT' => 60// 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'//'log.AdapterFactory' => '\PayPal\Log\DefaultLogFactory' // Factory class implementing \PayPal\Log\PayPalLogFactory));
step2: 创建设置订单,item代表一个订单,ItemList 用于存放多个订单统一支付,支付成功和取消都会跳回你设置的接口,订单创建后会生成一个跳转PayPal支付的地址,和订单号,用户访问该地址就可以在PayPal上操作支付了,具体代码如下:
$apiContext = $this->initPayPal(); // 获取配置好的ApiContext$itemList = new ItemList();$items = array();$total = 0;$product = 'test支付测试';$price = 0.01; // 金额$total = $total + $price ;$payer = new Payer();$payer->setPaymentMethod('paypal');$item = new Item();$item->setName($product)->setCurrency('HKD')->setQuantity(1)->setPrice($price);$items[] = $item;$itemList->setItems($items);$shipping = 0.00; //运费$total = $total + $shipping;$details = new Details();$details->setShipping($shipping)->setSubtotal($total);$amount = new Amount();$amount->setCurrency('HKD')->setTotal($total);$transaction = new Transaction();$transaction->setAmount($amount)->setItemList($itemList)->setDescription($product)->setInvoiceNumber(uniqid());$baseUrl = "http://localhost/home/order/test";$redirectUrls = new RedirectUrls();$redirectUrls->setReturnUrl($baseUrl.'?lz_type=1')->setCancelUrl($baseUrl.'?lz_type=2');$payment = new Payment();$payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction));try {$payment->create($apiContext); //错误点//} catch (PayPalConnectionException $e) {echo $e->getData();die();}$approvalUrl = $payment->getApprovalLink();$id = $payment->getId();$this->redirect($approvalUrl);