feat: Added payment.pay route and enhanced checkOut route controller to serve gateways to view

This commit is contained in:
IceToast 2023-01-03 21:17:25 +01:00
parent 16a7391372
commit 23cb226196
2 changed files with 28 additions and 198 deletions

View file

@ -35,6 +35,8 @@ use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
use PayPalHttp\HttpException;
use Stripe\Stripe;
use Symfony\Component\Intl\Currencies;
use App\Helpers\ExtensionHelper;
class PaymentController extends Controller
@ -57,6 +59,23 @@ class PaymentController extends Controller
*/
public function checkOut(Request $request, ShopProduct $shopProduct)
{
// get all payment gateway extensions
$extensions = glob(app_path() . '/Extensions/PaymentGateways/*', GLOB_ONLYDIR);
// build a paymentgateways array that contains the routes for the payment gateways and the image path for the payment gateway which lays in public/images/Extensions/PaymentGateways with the extensionname in lowercase
$paymentGateways = [];
foreach ($extensions as $extension) {
$extensionName = basename($extension);
$config = ExtensionHelper::getExtensionConfig($extensionName, 'PaymentGateways');
if ($config) {
$payment = new \stdClass();
$payment->name = $config['name'];
$payment->image = asset('images/Extensions/PaymentGateways/' . strtolower($extensionName) . '_logo.png');
$paymentGateways[] = $payment;
}
}
return view('store.checkout')->with([
'product' => $shopProduct,
'discountpercent' => PartnerDiscount::getDiscount(),
@ -64,210 +83,21 @@ class PaymentController extends Controller
'discountedprice' => $shopProduct->getPriceAfterDiscount(),
'taxvalue' => $shopProduct->getTaxValue(),
'taxpercent' => $shopProduct->getTaxPercent(),
'total' => $shopProduct->getTotalPrice()
'total' => $shopProduct->getTotalPrice(),
'paymentGateways' => $paymentGateways,
]);
}
/**
* @param Request $request
* @param ShopProduct $shopProduct
* @return RedirectResponse
*/
public function PaypalPay(Request $request, ShopProduct $shopProduct)
public function pay(Request $request)
{
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = [
"intent" => "CAPTURE",
"purchase_units" => [
[
"reference_id" => uniqid(),
"description" => $shopProduct->display . (PartnerDiscount::getDiscount()?(" (" . __('Discount') . " " . PartnerDiscount::getDiscount() . '%)'):""),
"amount" => [
"value" => $shopProduct->getTotalPrice(),
'currency_code' => strtoupper($shopProduct->currency_code),
'breakdown' => [
'item_total' =>
[
'currency_code' => strtoupper($shopProduct->currency_code),
'value' => $shopProduct->getPriceAfterDiscount(),
],
'tax_total' =>
[
'currency_code' => strtoupper($shopProduct->currency_code),
'value' => $shopProduct->getTaxValue(),
]
]
]
]
],
"application_context" => [
"cancel_url" => route('payment.Cancel'),
"return_url" => route('payment.PaypalSuccess', ['product' => $shopProduct->id]),
'brand_name' => config('app.name', 'Laravel'),
'shipping_preference' => 'NO_SHIPPING'
]
$product = ShopProduct::find($request->product_id);
$paymentGateway = $request->payment_method;
];
try {
// Call API with your client and get a response for your call
$response = $this->getPayPalClient()->execute($request);
return redirect()->away($response->result->links[1]->href);
// If call returns body in response, you can get the deserialized version from the result attribute of the response
} catch (HttpException $ex) {
echo $ex->statusCode;
dd(json_decode($ex->getMessage()));
}
}
/**
* @return PayPalHttpClient
*/
protected function getPayPalClient()
{
$environment = env('APP_ENV') == 'local'
? new SandboxEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret())
: new ProductionEnvironment($this->getPaypalClientId(), $this->getPaypalClientSecret());
return new PayPalHttpClient($environment);
}
/**
* @return string
*/
protected function getPaypalClientId()
{
return env('APP_ENV') == 'local' ? config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_CLIENT_ID") : config("SETTINGS::PAYMENTS:PAYPAL:CLIENT_ID");
}
/**
* @return string
*/
protected function getPaypalClientSecret()
{
return env('APP_ENV') == 'local' ? config("SETTINGS::PAYMENTS:PAYPAL:SANDBOX_SECRET") : config("SETTINGS::PAYMENTS:PAYPAL:SECRET");
}
/**
* @param Request $laravelRequest
*/
public function PaypalSuccess(Request $laravelRequest)
{
/** @var ShopProduct $shopProduct */
$shopProduct = ShopProduct::findOrFail($laravelRequest->input('product'));
/** @var User $user */
$user = Auth::user();
$request = new OrdersCaptureRequest($laravelRequest->input('token'));
$request->prefer('return=representation');
try {
// Call API with your client and get a response for your call
$response = $this->getPayPalClient()->execute($request);
if ($response->statusCode == 201 || $response->statusCode == 200) {
//update server limit
if (config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE') !== 0) {
if ($user->server_limit < config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')) {
$user->update(['server_limit' => config('SETTINGS::USER:SERVER_LIMIT_AFTER_IRL_PURCHASE')]);
}
}
//update User with bought item
if ($shopProduct->type=="Credits") {
$user->increment('credits', $shopProduct->quantity);
}elseif ($shopProduct->type=="Server slots"){
$user->increment('server_limit', $shopProduct->quantity);
}
//give referral commission always
if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE") == "both") && $shopProduct->type=="Credits" && config("SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION") == "true"){
if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){
$ref_user = User::findOrFail($ref_user->referral_id);
$increment = number_format($shopProduct->quantity*(PartnerDiscount::getCommission($ref_user->id))/100,0,"","");
$ref_user->increment('credits', $increment);
//LOGS REFERRALS IN THE ACTIVITY LOG
activity()
->performedOn($user)
->causedBy($ref_user)
->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
}
}
//update role give Referral-reward
if ($user->role == 'member') {
$user->update(['role' => 'client']);
//give referral commission only on first purchase
if((config("SETTINGS::REFERRAL:MODE") == "commission" || config("SETTINGS::REFERRAL:MODE") == "both") && $shopProduct->type=="Credits" && config("SETTINGS::REFERRAL::ALWAYS_GIVE_COMMISSION") == "false"){
if($ref_user = DB::table("user_referrals")->where('registered_user_id', '=', $user->id)->first()){
$ref_user = User::findOrFail($ref_user->referral_id);
$increment = number_format($shopProduct->quantity*(PartnerDiscount::getCommission($ref_user->id))/100,0,"","");
$ref_user->increment('credits', $increment);
//LOGS REFERRALS IN THE ACTIVITY LOG
activity()
->performedOn($user)
->causedBy($ref_user)
->log('gained '. $increment.' '.config("SETTINGS::SYSTEM:CREDITS_DISPLAY_NAME").' for commission-referral of '.$user->name.' (ID:'.$user->id.')');
}
}
}
//store payment
$payment = Payment::create([
'user_id' => $user->id,
'payment_id' => $response->result->id,
'payment_method' => 'paypal',
'type' => $shopProduct->type,
'status' => 'paid',
'amount' => $shopProduct->quantity,
'price' => $shopProduct->price - ($shopProduct->price*PartnerDiscount::getDiscount()/100),
'tax_value' => $shopProduct->getTaxValue(),
'tax_percent' => $shopProduct->getTaxPercent(),
'total_price' => $shopProduct->getTotalPrice(),
'currency_code' => $shopProduct->currency_code,
'shop_item_product_id' => $shopProduct->id,
]);
event(new UserUpdateCreditsEvent($user));
//only create invoice if SETTINGS::INVOICE:ENABLED is true
if (config('SETTINGS::INVOICE:ENABLED') == 'true') {
$this->createInvoice($user, $payment, 'paid', $shopProduct->currency_code);
}
//redirect back to home
return redirect()->route('home')->with('success', __('Your credit balance has been increased!'));
}
// If call returns body in response, you can get the deserialized version from the result attribute of the response
if (env('APP_ENV') == 'local') {
dd($response);
} else {
abort(500);
}
} catch (HttpException $ex) {
if (env('APP_ENV') == 'local') {
echo $ex->statusCode;
dd($ex->getMessage());
} else {
abort(422);
}
}
return redirect()->route('payment.' . $paymentGateway . 'Pay', ['shopProduct' => $product->id]);
}
/**
* @param Request $request

View file

@ -85,7 +85,7 @@ Route::middleware(['auth', 'checkSuspended'])->group(function () {
#payments
Route::get('checkout/{shopProduct}', [PaymentController::class, 'checkOut'])->name('checkout');
Route::get('payment/pay', [PaymentController::class, 'pay'])->name('payment.pay');
Route::post('payment/pay', [PaymentController::class, 'pay'])->name('payment.pay');
Route::get('payment/StripePay/{shopProduct}', [PaymentController::class, 'StripePay'])->name('payment.StripePay');
Route::get('payment/StripeSuccess', [PaymentController::class, 'StripeSuccess'])->name('payment.StripeSuccess');
Route::get('payment/Cancel', [PaymentController::class, 'Cancel'])->name('payment.Cancel');