Integration Completed

This commit is contained in:
devansh bawari 2020-11-18 18:40:29 +05:30
parent 41103f3b8e
commit 1222f5d14a
6 changed files with 249 additions and 166 deletions

View File

@ -1369,7 +1369,11 @@ return [
'custom-javascript' => 'Custom Javascript',
'paypal-smart-button' => 'PayPal',
'client-id' => 'Client Id',
'client-id-info' => 'Use "sb" for testing.'
'client-id-info' => 'Use "sb" for testing.',
'client-secret' => 'Client Secret',
'client-secret-info' => 'Add your secret key here',
'accepted-currencies' => 'Accepted currencies',
'accepted-currencies-info' => 'Add currency code comma seperated e.g. USD,INR,...'
]
]
];

View File

@ -86,6 +86,20 @@ return [
'type' => 'depends',
'depend' => 'active:1',
'validation' => 'required_if:active,1',
], [
'name' => 'client_secret',
'title' => 'admin::app.admin.system.client-secret',
'info' => 'admin::app.admin.system.client-secret-info',
'type' => 'depends',
'depend' => 'active:1',
'validation' => 'required_if:active,1',
], [
'name' => 'accepted_currencies',
'title' => 'admin::app.admin.system.accepted-currencies',
'info' => 'admin::app.admin.system.accepted-currencies',
'type' => 'depends',
'depend' => 'active:1',
'validation' => 'required_if:active,1',
], [
'name' => 'active',
'title' => 'admin::app.admin.system.status',
@ -93,7 +107,13 @@ return [
'validation' => 'required',
'channel_based' => false,
'locale_based' => true
], [
], [
'name' => 'sandbox',
'title' => 'admin::app.admin.system.sandbox',
'type' => 'boolean',
'channel_based' => false,
'locale_based' => true,
], [
'name' => 'sort',
'title' => 'admin::app.admin.system.sort_order',
'type' => 'select',

View File

@ -3,11 +3,20 @@
namespace Webkul\Paypal\Http\Controllers;
use Webkul\Checkout\Facades\Cart;
use Webkul\Paypal\Payment\SmartButton;
use Webkul\Sales\Repositories\OrderRepository;
use Webkul\Sales\Repositories\InvoiceRepository;
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
class SmartButtonController extends Controller
{
/**
* SmartButton object
*
* @var \Webkul\Paypal\Payment\SmartButton
*/
protected $smartButtonClient;
/**
* OrderRepository object
*
@ -30,6 +39,7 @@ class SmartButtonController extends Controller
* @return void
*/
public function __construct(
SmartButton $smartButtonClient,
OrderRepository $orderRepository,
InvoiceRepository $invoiceRepository
)
@ -37,14 +47,67 @@ class SmartButtonController extends Controller
$this->orderRepository = $orderRepository;
$this->invoiceRepository = $invoiceRepository;
$this->smartButtonClient = $smartButtonClient->client();
}
/**
* Success payment
* Success payment.
*
* @return \Illuminate\Http\JsonResponse
*/
public function details()
public function details(OrdersCreateRequest $request)
{
$request->prefer('return=representation');
$request->body = $this->buildRequestBody();
$response = $this->smartButtonClient->execute($request);
return response()->json($response);
}
/**
* Save order.
*
* @return \Illuminate\Http\Response
*/
public function saveOrder()
{
if (Cart::hasError()) {
return response()->json(['redirect_url' => route('shop.checkout.cart.index')], 403);
}
try {
Cart::collectTotals();
$this->validateOrder();
$order = $this->orderRepository->create(Cart::prepareDataForOrder());
$this->orderRepository->update(['status' => 'processing'], $order->id);
if ($order->canInvoice()) {
$this->invoiceRepository->create($this->prepareInvoiceData($order));
}
Cart::deActivateCart();
session()->flash('order', $order);
return response()->json([
'success' => true,
]);
} catch (\Exception $e) {
session()->flash('error', trans('shop::app.common.error'));
throw $e;
}
}
/**
* Build request body.
*
* @return array
*/
protected function buildRequestBody()
{
$cart = Cart::getCart();
@ -143,12 +206,12 @@ class SmartButtonController extends Controller
}
/**
* Return cart items
* Return cart items.
*
* @param string $cart
* @return array
*/
public function getLineItems($cart)
protected function getLineItems($cart)
{
$lineItems = [];
@ -169,12 +232,12 @@ class SmartButtonController extends Controller
}
/**
* Return convert multiple address lines into 2 address lines
* Return convert multiple address lines into 2 address lines.
*
* @param string $address
* @return array
*/
public function getAddressLines($address)
protected function getAddressLines($address)
{
$address = explode(PHP_EOL, $address, 2);
@ -190,47 +253,7 @@ class SmartButtonController extends Controller
}
/**
* Save order
*
* @return \Illuminate\Http\Response
*/
public function saveOrder()
{
if (Cart::hasError()) {
return response()->json(['redirect_url' => route('shop.checkout.cart.index')], 403);
}
try {
Cart::collectTotals();
$this->validateOrder();
$cart = Cart::getCart();
$order = $this->orderRepository->create(Cart::prepareDataForOrder());
$this->orderRepository->update(['status' => 'processing'], $order->id);
if ($order->canInvoice()) {
$invoice = $this->invoiceRepository->create($this->prepareInvoiceData($order));
}
Cart::deActivateCart();
session()->flash('order', $order);
return response()->json([
'success' => true,
]);
} catch (\Exception $e) {
session()->flash('error', trans('shop::app.common.error'));
throw $e;
}
}
/**
* Prepares order's invoice data for creation
* Prepares order's invoice data for creation.
*
* @param \Webkul\Sales\Models\Order $order
* @return array
@ -247,14 +270,20 @@ class SmartButtonController extends Controller
}
/**
* Validate order before creation
* Validate order before creation.
*
* @return void|\Exception
*/
public function validateOrder()
protected function validateOrder()
{
$cart = Cart::getCart();
$minimumOrderAmount = (int) core()->getConfigData('sales.orderSettings.minimum-order.minimum_order_amount') ?? 0;
if (! $cart->checkMinimumOrder()) {
throw new \Exception(trans('shop::app.checkout.cart.minimum-order-message', ['amount' => core()->currency($minimumOrderAmount)]));
}
if ($cart->haveStockableItems() && ! $cart->shipping_address) {
throw new \Exception(trans('Please check shipping address.'));
}

View File

@ -2,15 +2,41 @@
namespace Webkul\Paypal\Payment;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
use PayPalCheckoutSdk\Core\ProductionEnvironment;
class SmartButton extends Paypal
{
/**
* Payment method code
* Client ID.
*
* @var string
*/
protected $clientId;
/**
* Client secret.
*
* @var string
*/
protected $clientSecret;
/**
* Payment method code.
*
* @var string
*/
protected $code = 'paypal_smart_button';
/**
* Constructor.
*/
public function __construct()
{
$this->initialize();
}
/**
* Return paypal redirect url
*
@ -19,4 +45,39 @@ class SmartButton extends Paypal
public function getRedirectUrl()
{
}
/**
* Returns PayPal HTTP client instance with environment that has access
* credentials context. Use this instance to invoke PayPal APIs, provided the
* credentials have access.
*/
public function client()
{
return new PayPalHttpClient($this->environment());
}
/**
* Set up and return PayPal PHP SDK environment with PayPal access credentials.
* This sample uses SandboxEnvironment. In production, use LiveEnvironment.
*/
protected function environment()
{
$isSandbox = core()->getConfigData('sales.paymentmethods.paypal_smart_button.sandbox') ?: false;
if ($isSandbox) {
return new SandboxEnvironment($this->clientId, $this->clientSecret);
}
return new ProductionEnvironment($this->clientId, $this->clientSecret);
}
/**
* Initialize properties.
*/
protected function initialize()
{
$this->clientId = core()->getConfigData('sales.paymentmethods.paypal_smart_button.client_id') ?: '';
$this->clientSecret = core()->getConfigData('sales.paymentmethods.paypal_smart_button.client_secret') ?: '';
}
}

View File

@ -1,30 +0,0 @@
<?php
namespace Webkul\Paypal;
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
class PayPalClient
{
/**
* Returns PayPal HTTP client instance with environment that has access
* credentials context. Use this instance to invoke PayPal APIs, provided the
* credentials have access.
*/
public static function client()
{
return new PayPalHttpClient(self::environment());
}
/**
* Set up and return PayPal PHP SDK environment with PayPal access credentials.
* This sample uses SandboxEnvironment. In production, use LiveEnvironment.
*/
public static function environment()
{
$clientId = "Acr1C3OWYENmPT1ac0SpNvr5AFR_gMXI3pzcMnQzjV9ZW5E4M0A2teSUaipet384AotalP8KI-gwzbD0";
$clientSecret = "EMeh5Ai8A216ygPrs5AfKty_DyY3RMDBAemgqnrWkgYi5O9tq5chXI-PXsldYtO5Do4pEYYeqB66Hsdw";
return new SandboxEnvironment($clientId, $clientSecret);
}
}

View File

@ -1,96 +1,95 @@
@if (request()->route()->getName() == 'shop.checkout.onepage.index' && core()->getConfigData('sales.paymentmethods.paypal_smart_button.active'))
<script src="https://www.paypal.com/sdk/js?client-id={{core()->getConfigData('sales.paymentmethods.paypal_smart_button.client_id')}}" data-partner-attribution-id="Bagisto_Cart"></script>
@if (request()->route()->getName() == 'shop.checkout.onepage.index')
<style>
.component-frame.visible {
z-index: 1 !important;
}
</style>
@php
$clientId = core()->getConfigData('sales.paymentmethods.paypal_smart_button.client_id');
$acceptedCurrency = core()->getConfigData('sales.paymentmethods.paypal_smart_button.accepted_currencies');
@endphp
<script>
window.onload = (function() {
eventBus.$on('after-payment-method-selected', function(payment) {
if (payment.method != 'paypal_smart_button') {
$('.paypal-buttons').remove();
<script src="https://www.paypal.com/sdk/js?client-id={{ $clientId }}&currency={{ $acceptedCurrency }}" data-partner-attribution-id="Bagisto_Cart"></script>
return;
}
<style>
.component-frame.visible {
z-index: 1 !important;
}
</style>
if (typeof paypal == 'undefined') {
window.flashMessages = [{'type': 'alert-error', 'message': "SDK Validation error: 'client-id not recognized for either production or sandbox: {{core()->getConfigData('sales.paymentmethods.paypal_smart_button.client_id')}}'" }];
<script>
window.onload = (function() {
eventBus.$on('after-payment-method-selected', function(payment) {
if (payment.method != 'paypal_smart_button') {
$('.paypal-buttons').remove();
window.flashMessages.alertMessage = "SDK Validation error: 'client-id not recognized for either production or sandbox: {{core()->getConfigData('sales.paymentmethods.paypal_smart_button.client_id')}}'";
return;
}
app.addFlashMessages();
if (typeof paypal == 'undefined') {
window.flashMessages = [{'type': 'alert-error', 'message': "SDK Validation error: 'client-id not recognized for either production or sandbox: {{core()->getConfigData('sales.paymentmethods.paypal_smart_button.client_id')}}'" }];
return;
}
var options = {
style: {
layout: 'vertical',
shape: 'rect',
},
enableStandardCardFields: false,
createOrder: function(data, actions) {
return window.axios.get("{{ route('paypal.smart_button.details') }}")
.then(function(response) {
return actions.order.create(response.data);
})
.catch(function (error) {})
},
// Finalize the transaction
onApprove: function(data, actions) {
app.showLoader();
return actions.order.capture()
.then(function(response) {
if (response.error == 'INSTRUMENT_DECLINED') {
return actions.restart();
} else {
return response;
}
})
.then(function(details) {
return window.axios.post("{{ route('paypal.smart_button.save_order') }}", {
'_token': "{{ csrf_token() }}",
'data' : details
})
.then(function(response) {
if (response.data.success) {
if (response.data.redirect_url) {
window.location.href = response.data.redirect_url;
} else {
window.location.href = "{{ route('shop.checkout.success') }}";
}
}
app.hideLoader()
})
.catch(function (error) {
window.location.href = "{{ route('shop.checkout.cart.index') }}";
})
});
},
onCancel: function (data) {
console.log('Canceled payment')
},
onError: function (err) {
window.flashMessages = [{'type': 'alert-error', 'message': err }];
window.flashMessages.alertMessage = err;
window.flashMessages.alertMessage = "SDK Validation error: 'client-id not recognized for either production or sandbox: {{core()->getConfigData('sales.paymentmethods.paypal_smart_button.client_id')}}'";
app.addFlashMessages();
}
};
paypal.Buttons(options).render(".paypal-button-container");
return;
}
let options = {
style: {
layout: 'vertical',
shape: 'rect',
},
enableStandardCardFields: false,
createOrder: function(data, actions) {
return window.axios.get("{{ route('paypal.smart_button.details') }}")
.then(function(response) {
return response.data.result;
})
.then(function(orderData) {
return orderData.id;
})
.catch(function (error) {})
},
onApprove: function(data, actions) {
app.showLoader();
window.axios.post("{{ route('paypal.smart_button.save_order') }}", {
'_token': "{{ csrf_token() }}",
'data' : data
})
.then(function(response) {
if (response.data.success) {
if (response.data.redirect_url) {
window.location.href = response.data.redirect_url;
} else {
window.location.href = "{{ route('shop.checkout.success') }}";
}
}
app.hideLoader()
})
.catch(function (error) {
window.location.href = "{{ route('shop.checkout.cart.index') }}";
})
},
onCancel: function (data) {
console.log('Canceled payment...');
},
onError: function (err) {
window.flashMessages = [{'type': 'alert-error', 'message': err }];
window.flashMessages.alertMessage = err;
app.addFlashMessages();
}
};
paypal.Buttons(options).render('.paypal-button-container');
});
});
});
</script>
</script>
@endif