Недавно я пишу небольшой проект для иностранных покупателей. Поскольку он предназначен для иностранных покупателей, его необходимо использовать. PayPal Эта платежная платформа. Потому что в стыковке PayPal Есть некоторые проблемы в процессе стыковки, которые заняли некоторое время. Поэтому я записываю процесс стыковки и надеюсь, что это поможет нам его использовать. PayPal Друзья.
То, что я интегрирую,-это paypal /rest-api - sdk - php . PayPal Из api Да v1 и v2 Две версии. Этот, который я использую, v1 Издание.
Следующее показано в виде кода, без скриншотов, но я пытаюсь объяснить это в коде. Предположим, вы уже полезны. laravel Напиши проект:
Шаг:1 Пакет Расширения для Установки
composer require paypal/rest-api-sdk-php
Шаг:2 Установите payment.php файл конфигурации
оставайтесь Конфигурация Новый каталог payment.php Файл конфигурации, следующий
return [
'paypal' => [
/** set your paypal credential **/
'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',
/**
* SDK configuration
*/
'settings' => array(
/**
* Sandbox test'sandbox'or'live'
*/
'mode' => 'sandbox',
/**
* Request timeout
*/
'http.ConnectionTimeOut' => 1000,
/**
* Whether to open logs: true open, false not open
*/
'log.LogEnabled' => true,
/**
* Log-stored files
*/
'log.FileName' => storage_path() . '/logs/paypal.log',
/**
* Log level'DEBUG','INFO','WARN'or'ERROR'
*
*/
'log.LogLevel' => 'INFO'
),
],
'2checkout' => [
//
]
];Шаг:3 Создайте маршрут
// Step 1: Display the form. This is a simple form page. We enter the amount and then click Submit.
Route::get('paypal-form', 'Payment\[email protected]')->name('paypal-form');
// Step 2: The first step is to send a request after submission, requesting this method, which is used to create an order and a payment process.
Route::post('paypal-pay', 'Payment\[email protected]')->name('payment.paypay.pay');
// Step 3: Asynchronous callback
Route::post('paypal-notify', 'Payment\[email protected]')->name('payment.paypal.notify');
// Step 3: Front-end callback
Route::get('paypal-return', 'Payment\[email protected]')->name('payment.paypal.return');
// Step 3: Cancel
Route::get('paypal-cancel', 'Payment\[email protected]')->name('payment.paypal.cancel');Шаг:3 Создайте контроллер
_api_context = new ApiContext(new OAuthTokenCredential(
$payPal_config['client_id'],
$payPal_config['secret']
));
$this->_api_context->setConfig($payPal_config['setting']);
}
// Display forms
public function payPalShow()
{
return view('payment.paypal');
}
// Step two, request here
public function pay(Request $request)
{
$payer = new Payer();
$payer->setPaymentMethod('paypal');
// Product Name, Currency, Quantity, Single Product Amount
$item1 = new Item();
$item1->setName('item1')
->setCurrency('USD')
->setQuantity(1)
->setPrice($request->get('amount'));
// Collecting all products into ItemList
$item_list = new ItemList();
$item_list->setItems([$item1]);
$amount = new Amount();
$amount->setCurrency('USD')
->setTotal($request->get('amount'));
// Generate a transaction
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
-> setDescription ('Your Transaction')
-> SetNotifyUrl (route ('notify_url')// Note that the asynchronous callback address is set here
-> setInvoiceNumber ($order - > order_number); // Set the order number here
// Setting Front-end Callback Address and Canceling Payment Address
$redirect_urls = new RedirectUrls();
$redirect_urls->setReturnUrl(route('payment.paypal.return'))
->setCancelUrl(route('payment.paypal.cancel'));
$payment = new Payment();
$payment->setIntent('Sale')
->setPayer($payer)
->setRedirectUrls($redirect_urls)
->setTransactions(array($transaction));try {
// Here the payment process is generated
$payment->create($this->_api_context);
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
if (config('app.debug')) {
session()->put('error','Connection timeout');
return redirect()->route('paypal-form');
/** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/
/** $err_data = json_decode($ex->getData(), true); **/
/** exit; **/
} else {
session()->put('error','Some error occur, sorry for inconvenient');
return redirect()->route('paypal-form');
}
}
foreach($payment->getLinks() as $link) {
if($link->getRel() == 'approval_url') {
$redirect_url = $link->getHref();
break;
}
}
// $payment - > getId () gets the payment line number
session()->put('paypal_payment_id', $payment->getId());
if(isset($redirect_url)) {
// Jump to Payment Page
return redirect()->away($redirect_url);
}
session()->put('error','Unknown error occurred');
return session()->route('paypal-form');
}
public function payPalReturn(Request $request)
{
// After successful payment, when the front page jumps back, the URL address will have paymentID and PayerrID
$payment_id = session()->get('paypal_payment_id');
session()->forget('paypal_payment_id');
if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
session()->put('error','Payment failed');
return redirect()->route('paypal-form');
}
$payment = Payment::get($payment_id, $this->_api_context);
$execution = new PaymentExecution();
$execution->setPayerId(Input::get('PayerID'));
$result = $payment->execute($execution, $this->_api_context);
// Approved indicates successful payment when the status is received
if ($result->getState() == 'approved') {
session()->put('success','Payment success');
return redirect()->route('paypal-form');
}
session()->put('error','Payment failed');
return redirect()->route('paypal-form');
}
public function payPalNotify()
{
Log::info(12312, Input::get());
// Here we write our business logic, order status updates, logistics information and so on.
}
}Шаг:4 создайте форму
Это было, когда я работал над проектом торгового центра. PayPal Из-за плохого английского языка возникнет много проблем при разработке процесса стыковки. Если английский хороший, я хотел бы знать больше об использовании. PayPal Документация для разработчиков и демонстрация Демонстрация.