Skip to content

Payment method order place #489

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 7 additions & 28 deletions Postman_APIs/Collections/GraphQL-API.postman_collection.json

Large diffs are not rendered by default.

112 changes: 112 additions & 0 deletions src/Helper/PaymentHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php

namespace Webkul\GraphQLAPI\Helper;

use Illuminate\Support\Facades\DB;
use Webkul\Paypal\Payment\SmartButton;
use Webkul\Sales\Repositories\OrderRepository;
use Webkul\Sales\Repositories\InvoiceRepository;

class PaymentHelper
{
/**
* Create a new helper instance.
*
* @return void
*/
public function __construct(
protected OrderRepository $orderRepository,
protected InvoiceRepository $invoiceRepository,
protected SmartButton $smartButton,
) {}

public function createInvoice($cart, $paymentDetail, $order)
{
if (
! empty($paymentDetail['error'])
|| $paymentDetail['message'] != "Success"
|| $cart->payment->method != $paymentDetail['payment_method']
) {
return;
}

$paymentMethod = $cart->payment->method;
$paymentIsCompleted = false;

match ($paymentMethod) {
'paypal_standard' => $paymentIsCompleted = $this->isNewTransaction($paymentDetail['txn_id']) && $this->checkPaypalPaymentStatus($paymentDetail['txn_id']),
'paypal_smart_button' => $paymentIsCompleted = $this->isNewTransaction($paymentDetail['orderID']) && $this->checkSmartButtonPaymentStatus($paymentDetail['orderID']),
default => null,
};

if (
$paymentIsCompleted
&& $order->canInvoice()
) {
request()->merge($paymentDetail);

$this->invoiceRepository->create($this->prepareInvoiceData($order));

$this->orderRepository->update(['status' => 'processing'], $order->id);
}
}

/**
* Prepares order's invoice data for creation.
*
* @return array
*/
protected function prepareInvoiceData($order)
{
$invoiceData = ['order_id' => $order->id];

foreach ($order->items as $item) {
$invoiceData['invoice']['items'][$item->id] = $item->qty_to_invoice;
}

return $invoiceData;
}

protected function isNewTransaction(string $transactionId): bool
{
return ! DB::table('order_transactions')->where('transaction_id', $transactionId)->exists();
}

protected function checkPaypalPaymentStatus($paymentId)
{
$clientId = core()->getConfigData('sales.payment_methods.paypal_standard.client_id');
$secretKey = core()->getConfigData('sales.payment_methods.paypal_standard.client_secret');
$sandbox = core()->getConfigData('sales.payment_methods.paypal_standard.sandbox');

$url = $sandbox
? "https://api-m.sandbox.paypal.com/v1/payments/payment/{$paymentId}"
: "https://api-m.paypal.com/v1/payments/payment/{$paymentId}";

$curl = curl_init($url);
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FAILONERROR => true,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Basic ' . base64_encode("{$clientId}:{$secretKey}"),
],
]);

$response = curl_exec($curl);
curl_close($curl);

if ($response) {
$responseData = json_decode($response, true);
return $responseData['state'] ?? '' === 'approved';
}

return false;
}

public function checkSmartButtonPaymentStatus(string $orderId): bool
{
$transactionDetails = json_decode(json_encode($this->smartButton->getOrder($orderId)), true);

return $transactionDetails['statusCode'] ?? 0 === 200;
}
}
10 changes: 5 additions & 5 deletions src/Mutations/Admin/Catalog/Products/ProductMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,8 @@ public function validateFormData(int $id, array $data)
'special_price_to' => 'nullable|date|after_or_equal:special_price_from',
'special_price' => ['nullable', new Decimal, 'lt:price'],
]);

foreach ($product->getEditableAttributes() as $attribute) {
foreach ($product->getEditableAttributes() as $attribute) {
if (
$attribute->code == 'sku'
|| $attribute->type == 'boolean'
Expand Down Expand Up @@ -321,10 +321,10 @@ public function validateFormData(int $id, array $data)
}

if ($attribute->is_unique) {
array_push($validations, function ($field, $value, $fail) use ($attribute, $id) {
array_push($validations, function ($field, $value, $fail) use ($attribute, $id, $data) {
$column = ProductAttributeValue::$attributeTypeFields[$attribute->type];

if (! $this->productAttributeValueRepository->isValueUnique($id, $attribute->id, $column, request($attribute->code))) {
if (! $this->productAttributeValueRepository->isValueUnique($id, $attribute->id, $column, $data[$attribute->code])) {
$fail('The :attribute has already been taken.');
}
});
Expand Down
23 changes: 11 additions & 12 deletions src/Mutations/Admin/Customer/CustomerAddressMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public function store(mixed $rootValue, array $args, GraphQLContext $context)

return [
'success' => true,
'message' => trans('bagisto_graphql::app.admin.customers.addressess.create-success'),
'message' => trans('bagisto_graphql::app.admin.customers.addresses.create-success'),
'address' => $customerAddress,
];
} catch (\Exception $e) {
Expand Down Expand Up @@ -112,7 +112,7 @@ public function update(mixed $rootValue, array $args, GraphQLContext $context)
$customerAddress = $this->customerAddressRepository->find($args['id']);

if (! $customerAddress) {
throw new CustomException(trans('bagisto_graphql::app.admin.customers.addressess.not-found'));
throw new CustomException(trans('bagisto_graphql::app.admin.customers.addresses.not-found'));
}

try {
Expand All @@ -124,7 +124,7 @@ public function update(mixed $rootValue, array $args, GraphQLContext $context)

return [
'success' => true,
'message' => trans('bagisto_graphql::app.admin.customers.addressess.update-success'),
'message' => trans('bagisto_graphql::app.admin.customers.addresses.update-success'),
'address' => $customerAddress,
];
} catch (\Exception $e) {
Expand All @@ -145,7 +145,11 @@ public function setAsDefaultAddress(mixed $rootValue, array $args, GraphQLContex
]);

if (! $address) {
throw new CustomException(trans('bagisto_graphql::app.admin.customers.addressess.not-found'));
throw new CustomException(trans('bagisto_graphql::app.admin.customers.addresses.not-found'));
}

if ($address->default_address) {
throw new CustomException(trans('bagisto_graphql::app.admin.customers.addresses.already-default'));
}

try {
Expand All @@ -154,16 +158,11 @@ public function setAsDefaultAddress(mixed $rootValue, array $args, GraphQLContex
'default_address' => 1,
])->update(['default_address' => 0]);

$address = $this->customerAddressRepository->findOnewhere([
'id' => $args['id'],
'customer_id' => $args['customer_id'],
]);

$address->update(['default_address' => 1]);

return [
'success' => true,
'message' => trans('bagisto_graphql::app.admin.customers.addressess.default-update-success'),
'message' => trans('bagisto_graphql::app.admin.customers.addresses.default-update-success'),
'address' => $address,
];
} catch (\Exception $e) {
Expand All @@ -183,7 +182,7 @@ public function delete(mixed $rootValue, array $args, GraphQLContext $context)
$customerAddress = $this->customerAddressRepository->find($args['id']);

if (! $customerAddress) {
throw new CustomException(trans('bagisto_graphql::app.admin.customers.addressess.not-found'));
throw new CustomException(trans('bagisto_graphql::app.admin.customers.addresses.not-found'));
}

try {
Expand All @@ -195,7 +194,7 @@ public function delete(mixed $rootValue, array $args, GraphQLContext $context)

return [
'success' => true,
'message' => trans('bagisto_graphql::app.admin.customers.addressess.delete-success'),
'message' => trans('bagisto_graphql::app.admin.customers.addresses.delete-success'),
];

} catch (\Exception $e) {
Expand Down
2 changes: 1 addition & 1 deletion src/Mutations/Shop/Customer/AddressesMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ public function setDefaultAddress(mixed $rootValue, array $args, GraphQLContext

return [
'success' => true,
'message' => trans('bagisto_graphql::app.admin.customers.addressess.default-update-success'),
'message' => trans('bagisto_graphql::app.admin.customers.addresses.default-update-success'),
'address' => $address,
];
} catch (\Exception $e) {
Expand Down
75 changes: 10 additions & 65 deletions src/Mutations/Shop/Customer/CheckoutMutation.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@

use Webkul\Core\Rules\PostCode;
use Webkul\Checkout\Facades\Cart;
use Illuminate\Support\Facades\DB;
use Webkul\Core\Rules\PhoneNumber;
use Webkul\Payment\Facades\Payment;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Webkul\Shipping\Facades\Shipping;
use Webkul\GraphQLAPI\Helper\PaymentHelper;
use Webkul\Sales\Transformers\OrderResource;
use Webkul\Sales\Repositories\OrderRepository;
use Webkul\Sales\Repositories\InvoiceRepository;
Expand All @@ -30,7 +32,8 @@ public function __construct(
protected CustomerAddressRepository $customerAddressRepository,
protected OrderRepository $orderRepository,
protected NotificationRepository $notificationRepository,
protected InvoiceRepository $invoiceRepository
protected InvoiceRepository $invoiceRepository,
protected PaymentHelper $paymentHelper
) {
Auth::setDefaultDriver('api');
}
Expand Down Expand Up @@ -470,24 +473,16 @@ public function saveOrder(mixed $rootValue, array $args, GraphQLContext $context

$cart = Cart::getCart();

if (
! $args['is_payment_required']
&& $redirectUrl = Payment::getRedirectUrl($cart)
) {
return [
'success' => true,
'redirect_url' => $redirectUrl,
'selected_method' => $cart->payment->method,
];
}

$data = (new OrderResource($cart))->jsonSerialize();

$order = $this->orderRepository->create($data);
$orderData = (new OrderResource($cart))->jsonSerialize();
$order = $this->orderRepository->create($orderData);

if (core()->getConfigData('general.api.pushnotification.private_key')) {
$this->prepareNotificationContent($order);
}

if (! empty($args['is_payment_completed'])) {
$this->paymentHelper->createInvoice($cart, $args, $order);
}

Cart::deActivateCart();

Expand Down Expand Up @@ -558,54 +553,4 @@ public function prepareNotificationContent($order)

$this->notificationRepository->sendNotification($data, $notification);
}

/**
* Create charge
*
* @return array
*
* @throws CustomException
*/
public function createCharge()
{
if (! $cart = Cart::getCart()) {
throw new CustomException(trans('bagisto_graphql::app.shop.checkout.something-wrong'));
}

$order = $this->orderRepository->create((new OrderResource($cart))->jsonSerialize());

$order = $this->orderRepository->findOneByField('cart_id', $cart->id);

$this->orderRepository->update(['status' => 'processing'], $order->id);

if ($order->canInvoice()) {
$this->invoiceRepository->create($this->prepareInvoiceData($order));
}

Cart::deActivateCart();

return [
'success' => true,
'order' => $order,
];
}

/**
* Prepares order's invoice data for creation
*
* @param \Webkul\Sales\Contracts\Order $order
* @return array
*/
public function prepareInvoiceData($order)
{
$invoiceData = [
'order_id' => $order->id,
];

foreach ($order->items as $item) {
$invoiceData['invoice']['items'][$item->id] = $item->qty_to_invoice;
}

return $invoiceData;
}
}
9 changes: 6 additions & 3 deletions src/Resources/lang/ar/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
'delete-success' => 'تم حذف عنوان العميل بنجاح',
'not-found' => 'تحذير: لم يتم العثور على العنوان.',
'update-success' => 'تم تحديث العنوان بنجاح.',
'already-default' => 'تحذير: هذا العنوان تم تعيينه كافتراضي بالفعل.',
],

'wishlist' => [
Expand Down Expand Up @@ -362,12 +363,14 @@
'login-success' => 'تم تسجيل الدخول بنجاح.',
],

'addressess' => [
'addresses' => [
'create-success' => 'تم إنشاء عنوان العميل بنجاح.',
'default-update-success' => 'تم تعيين العنوان كافتراضي',
'delete-success' => 'تم حذف عنوان العميل بنجاح',
'default-update-success' => 'تم تعيين العنوان كافتراضي.',
'delete-success' => 'تم حذف عنوان العميل بنجاح.',
'not-found' => 'تحذير: عنوان العميل غير موجود.',
'update-success' => 'تم تحديث عنوان العميل بنجاح.',
'already-default' => 'تحذير: هذا العنوان تم تعيينه كافتراضي بالفعل.',
],
],

'groups' => [
Expand Down
9 changes: 6 additions & 3 deletions src/Resources/lang/bn/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
'delete-success' => 'ঠিকানা সফলভাবে মোছা হয়েছে',
'not-found' => 'সতর্কবার্তা: ঠিকানা পাওয়া যায়নি।',
'update-success' => 'ঠিকানা সফলভাবে আপডেট হয়েছে।',
'already-default' => 'সতর্কবার্তা: এই ঠিকানাটি ইতিমধ্যেই ডিফল্ট হিসাবে সেট করা হয়েছে।',
],

'wishlist' => [
Expand Down Expand Up @@ -362,12 +363,14 @@
'login-success' => 'গ্রাহক সফলভাবে লগইন হয়েছে।',
],

'addressess' => [
'addresses' => [
'create-success' => 'গ্রাহকের ঠিকানা সফলভাবে তৈরি হয়েছে।',
'default-update-success' => 'ঠিকানা ডিফল্ট হিসাবে সেট করা হয়েছে',
'delete-success' => 'গ্রাহকের ঠিকানা সফলভাবে মুছে ফেলা হয়েছে',
'default-update-success' => 'ঠিকানা ডিফল্ট হিসাবে সেট করা হয়েছে',
'delete-success' => 'গ্রাহকের ঠিকানা সফলভাবে মুছে ফেলা হয়েছে',
'not-found' => 'সতর্কবার্তা: গ্রাহকের ঠিকানা পাওয়া যায়নি।',
'update-success' => 'গ্রাহকের ঠিকানা সফলভাবে আপডেট হয়েছে।',
'already-default' => 'সতর্কবার্তা: এই ঠিকানাটি ইতিমধ্যেই ডিফল্ট হিসাবে সেট করা হয়েছে।',
],
],

'groups' => [
Expand Down
Loading