Skip to content

Commit 9c42b8b

Browse files
committed
payment method flow completed
1 parent 5fb1454 commit 9c42b8b

File tree

4 files changed

+54
-86
lines changed

4 files changed

+54
-86
lines changed

Postman_APIs/Collections/GraphQL-API.postman_collection.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10654,7 +10654,7 @@
1065410654
"body": {
1065510655
"mode": "graphql",
1065610656
"graphql": {
10657-
"query": "mutation placeOrder {\n placeOrder (\n isPaymentCompleted: true\n error: false\n message: \"Success\"\n transactionId: \"PAYID-NA3LUPI8RM83901H3162294C\"\n paymentStatus: \"Completed\"\n paymentMethod: \"paypal_standard\"\n\n ) {\n success\n redirectUrl\n selectedMethod\n order {\n id\n customerEmail\n customerFirstName\n customerLastName\n }\n }\n}",
10657+
"query": "mutation placeOrder {\n placeOrder (\n isPaymentCompleted: true\n # Paypal Standard\n error: false\n message: \"Success\"\n transactionId: \"PAYID-NA3LUPI8RM83901H3162294C\"\n paymentStatus: \"Completed\"\n paymentType: \"instant\"\n paymentMethod: \"paypal_standard\"\n # Paypal Smart Button\n orderID: \"xyz\"\n ) {\n success\n redirectUrl\n selectedMethod\n order {\n id\n customerEmail\n customerFirstName\n customerLastName\n }\n }\n}",
1065810658
"variables": ""
1065910659
}
1066010660
},

src/Helper/PaymentHelper.php

Lines changed: 45 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
namespace Webkul\GraphQLAPI\Helper;
44

5+
use Illuminate\Support\Facades\DB;
6+
use Webkul\Paypal\Payment\SmartButton;
57
use Webkul\Sales\Repositories\OrderRepository;
68
use Webkul\Sales\Repositories\InvoiceRepository;
79

@@ -14,7 +16,8 @@ class PaymentHelper
1416
*/
1517
public function __construct(
1618
protected OrderRepository $orderRepository,
17-
protected InvoiceRepository $invoiceRepository
19+
protected InvoiceRepository $invoiceRepository,
20+
protected SmartButton $smartButton,
1821
) {}
1922

2023
public function createInvoice($cart, $paymentDetail, $order)
@@ -26,24 +29,25 @@ public function createInvoice($cart, $paymentDetail, $order)
2629
) {
2730
return;
2831
}
29-
32+
3033
$paymentMethod = $cart->payment->method;
31-
3234
$paymentIsCompleted = false;
3335

36+
match ($paymentMethod) {
37+
'paypal_standard' => $paymentIsCompleted = $this->isNewTransaction($paymentDetail['txn_id']) && $this->checkPaypalPaymentStatus($paymentDetail['txn_id']),
38+
'paypal_smart_button' => $paymentIsCompleted = $this->isNewTransaction($paymentDetail['orderID']) && $this->checkSmartButtonPaymentStatus($paymentDetail['orderID']),
39+
default => null,
40+
};
41+
3442
if (
35-
$paymentMethod == 'paypal_standard'
36-
|| $paymentMethod == 'paypal_smart_button'
43+
$paymentIsCompleted
44+
&& $order->canInvoice()
3745
) {
38-
$paymentIsCompleted = $this->checkPaypalPaymentStatus($paymentDetail['transaction_id']);
39-
}
40-
41-
if ($paymentIsCompleted) {
42-
$this->orderRepository->update(['status' => 'processing'], $order->id);
46+
request()->merge($paymentDetail);
47+
48+
$this->invoiceRepository->create($this->prepareInvoiceData($order));
4349

44-
if ($order->canInvoice()) {
45-
$invoice = $this->invoiceRepository->create($this->prepareInvoiceData($order));
46-
}
50+
$this->orderRepository->update(['status' => 'processing'], $order->id);
4751
}
4852
}
4953

@@ -63,37 +67,46 @@ protected function prepareInvoiceData($order)
6367
return $invoiceData;
6468
}
6569

66-
private function checkPaypalPaymentStatus($paymentId)
70+
protected function isNewTransaction(string $transactionId): bool
71+
{
72+
return ! DB::table('order_transactions')->where('transaction_id', $transactionId)->exists();
73+
}
74+
75+
protected function checkPaypalPaymentStatus($paymentId)
6776
{
6877
$clientId = core()->getConfigData('sales.payment_methods.paypal_standard.client_id');
6978
$secretKey = core()->getConfigData('sales.payment_methods.paypal_standard.client_secret');
79+
$sandbox = core()->getConfigData('sales.payment_methods.paypal_standard.sandbox');
7080

71-
if (core()->getConfigData('sales.payment_methods.paypal_standard.sandbox')) {
72-
$url = "https://api-m.sandbox.paypal.com/v1/payments/payment/{$paymentId}";
73-
} else {
74-
$url = "https://api-m.paypal.com/v1/payments/payment/{$paymentId}";
75-
}
81+
$url = $sandbox
82+
? "https://api-m.sandbox.paypal.com/v1/payments/payment/{$paymentId}"
83+
: "https://api-m.paypal.com/v1/payments/payment/{$paymentId}";
7684

7785
$curl = curl_init($url);
78-
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
79-
curl_setopt($curl, CURLOPT_HTTPHEADER, [
80-
'Content-Type: application/json',
81-
'Authorization: Basic ' . base64_encode("{$clientId}:{$secretKey}"),
86+
curl_setopt_array($curl, [
87+
CURLOPT_RETURNTRANSFER => true,
88+
CURLOPT_FAILONERROR => true,
89+
CURLOPT_HTTPHEADER => [
90+
'Content-Type: application/json',
91+
'Authorization: Basic ' . base64_encode("{$clientId}:{$secretKey}"),
92+
],
8293
]);
8394

8495
$response = curl_exec($curl);
85-
86-
if (curl_errno($curl)) {
87-
throw new \Exception('Curl error: ' . curl_error($curl));
88-
}
8996
curl_close($curl);
9097

91-
$responseData = json_decode($response, true);
92-
93-
if (isset($responseData['state']) && $responseData['state'] == 'approved') {
94-
return true;
98+
if ($response) {
99+
$responseData = json_decode($response, true);
100+
return $responseData['state'] ?? '' === 'approved';
95101
}
96-
102+
97103
return false;
98104
}
105+
106+
public function checkSmartButtonPaymentStatus(string $orderId): bool
107+
{
108+
$transactionDetails = json_decode(json_encode($this->smartButton->getOrder($orderId)), true);
109+
110+
return $transactionDetails['statusCode'] ?? 0 === 200;
111+
}
99112
}

src/Mutations/Shop/Customer/CheckoutMutation.php

Lines changed: 5 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,20 @@
44

55
use Webkul\Core\Rules\PostCode;
66
use Webkul\Checkout\Facades\Cart;
7+
use Illuminate\Support\Facades\DB;
78
use Webkul\Core\Rules\PhoneNumber;
89
use Webkul\Payment\Facades\Payment;
910
use App\Http\Controllers\Controller;
1011
use Illuminate\Support\Facades\Auth;
1112
use Webkul\Shipping\Facades\Shipping;
13+
use Webkul\GraphQLAPI\Helper\PaymentHelper;
1214
use Webkul\Sales\Transformers\OrderResource;
1315
use Webkul\Sales\Repositories\OrderRepository;
1416
use Webkul\Sales\Repositories\InvoiceRepository;
1517
use Webkul\GraphQLAPI\Validators\CustomException;
1618
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;
1719
use Webkul\CartRule\Repositories\CartRuleCouponRepository;
1820
use Webkul\GraphQLAPI\Repositories\NotificationRepository;
19-
use Webkul\GraphQLAPI\Helper\PaymentHelper;
2021
use Webkul\Customer\Repositories\CustomerAddressRepository;
2122

2223
class CheckoutMutation extends Controller
@@ -461,34 +462,6 @@ public function removeCoupon(mixed $rootValue, array $args, GraphQLContext $cont
461462
*/
462463
public function saveOrder(mixed $rootValue, array $args, GraphQLContext $context)
463464
{
464-
$mode = core()->getConfigData('sales.payment_methods.paypal_standard.sandbox') ? 'sandbox' : 'live';
465-
466-
$clientId = core()->getConfigData('sales.payment_methods.paypal_standard.client_id');
467-
$secret = core()->getConfigData('sales.payment_methods.paypal_standard.client_secret');
468-
469-
// Step 1: Get Access Token
470-
$client = new \GuzzleHttp\Client();
471-
472-
$authResponse = $client->post('https://api.sandbox.paypal.com/v1/oauth2/token', [
473-
'auth' => [$clientId, $secret],
474-
'form_params' => [
475-
'grant_type' => 'client_credentials',
476-
],
477-
]);
478-
479-
$authData = json_decode($authResponse->getBody(), true);
480-
$accessToken = $authData['access_token'];
481-
482-
// Step 2: Get Sale Info
483-
$saleResponse = $client->get("https://api.sandbox.paypal.com/v1/payments/sale/3HV05507FK9784747", [
484-
'headers' => [
485-
'Authorization' => "Bearer {$accessToken}",
486-
'Content-Type' => 'application/json',
487-
]
488-
]);
489-
490-
$saleData = json_decode($saleResponse->getBody(), true);
491-
dd($saleData);
492465
try {
493466
if (Cart::hasError()) {
494467
throw new CustomException(trans('bagisto_graphql::app.shop.checkout.something-wrong'));
@@ -500,15 +473,14 @@ public function saveOrder(mixed $rootValue, array $args, GraphQLContext $context
500473

501474
$cart = Cart::getCart();
502475

503-
$data = (new OrderResource($cart))->jsonSerialize();
504-
505-
$order = $this->orderRepository->create($data);
476+
$orderData = (new OrderResource($cart))->jsonSerialize();
477+
$order = $this->orderRepository->create($orderData);
506478

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

511-
if ($args['is_payment_completed']) {
483+
if (! empty($args['is_payment_completed'])) {
512484
$this->paymentHelper->createInvoice($cart, $args, $order);
513485
}
514486

@@ -581,23 +553,4 @@ public function prepareNotificationContent($order)
581553

582554
$this->notificationRepository->sendNotification($data, $notification);
583555
}
584-
585-
/**
586-
* Prepares order's invoice data for creation
587-
*
588-
* @param \Webkul\Sales\Contracts\Order $order
589-
* @return array
590-
*/
591-
public function prepareInvoiceData($order)
592-
{
593-
$invoiceData = [
594-
'order_id' => $order->id,
595-
];
596-
597-
foreach ($order->items as $item) {
598-
$invoiceData['invoice']['items'][$item->id] = $item->qty_to_invoice;
599-
}
600-
601-
return $invoiceData;
602-
}
603556
}

src/graphql/shop/checkout/place_order.graphql

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@ extend type Mutation {
44
isPaymentCompleted: Boolean = false @rename(attribute: "is_payment_completed")
55
error: Boolean = true
66
message: String
7-
transactionId: String @rename(attribute: "transaction_id")
7+
transactionId: String @rename(attribute: "txn_id")
88
paymentStatus: String @rename(attribute: "payment_status")
99
paymentMethod: String @rename(attribute: "payment_method")
10+
paymentType: String @rename(attribute: "payment_type")
11+
orderID: String @rename(attribute: "order_id")
1012
): PlacedOrderResponse @field(resolver: "Webkul\\GraphQLAPI\\Mutations\\Shop\\Customer\\CheckoutMutation@saveOrder")
1113
}
1214

0 commit comments

Comments
 (0)