Pārlūkot izejas kodu

修改支付方式

llp 1 nedēļu atpakaļ
vecāks
revīzija
afdb039096

+ 13 - 102
packages/Longyi/Pay/Applepay/src/Http/Controllers/ApplepayController.php

@@ -20,111 +20,22 @@ class ApplepayController extends Controller
         protected Applepay $applepay,
     ) {}
 
-    /**
-     * Redirects to the klarna.
-     *
-     * @return \Illuminate\View\View
-     */
-    public function placeOrder()
-    {
-        $cart = Cart::getCart();
-        $data = (new OrderResource($cart))->jsonSerialize();
-        $order = $this->orderRepository->create($data);
-        Cart::deActivateCart();
-        session()->flash('order_id', $order->id);
-        return view('AwxKlarna::standard-redirect', ['order' => $order]);
-    }
-
-    public function redirect()
-    {
-        $orderId = request()->input('orderId');
-        if (!$orderId) {
-            return response()->json([
-                'error' => 'Order ID is required'
-            ], 400);
-        }
-        $order = $this->orderRepository->find($orderId);
-        if (!$order) {
-            return response()->json([
-                'error' => 'Order not found'
-            ], 404);
-        }
-        if ($order->status != Order::STATUS_PENDING) {
-            return response()->json([
-                'error' => 'No payment required for the order'
-            ], 404);
-        }
-        $cartData = [
-            'shipping_address' => $order->shipping_address ? $order->shipping_address->toArray() : [],
-            'billing_address' => $order->billing_address ? $order->billing_address->toArray() : [],
-            'grand_total' => $order->grand_total,
-            'order_currency_code' => $order->order_currency_code,
-            'customer_email' => $order->customer_email,
-            'customer_first_name' => $order->customer_first_name,
-            'customer_last_name' => $order->customer_last_name
-        ];
-        try {
-            $checkoutUrl = $this->awxKlarna->createPayment($cartData, [
-                'merchantOrderId' => $order->id
-            ]);
-            if (!$checkoutUrl) {
-                throw new \Exception('Failed to get checkout URL from Airwallex');
-            }
-            return redirect()->away($checkoutUrl);
-        } catch (\Exception $e) {
-            return response()->json([
-                'error' => 'Payment initialization failed: ' . $e->getMessage()
-            ], 500);
-        }
-    }
-    /**
-     * Success payment.
-     *
-     * @return \Illuminate\Http\Response
-     */
-    public function return()
-    {
-        $awxReturnResult = request()->input('awx_return_result');
-        $orderId = request()->input('orderId');
-        if ($awxReturnResult == 'success') {
-            session()->flash('order_id', $orderId);
-            return redirect()->route('shop.checkout.onepage.success');
-        } else {
-            session()->flash('error', 'afterpay cancel');
-            return redirect()->route('shop.checkout.cart.index');
-        }
-    }
-
     public function hook()
     {
-        $param = @file_get_contents('php://input');
-        $header = $this->getAllHeaders();
-        $data = [
-            'timestamp' => $header['x-timestamp'],
-            'signature' => $header['x-signature'],
-            'content' => $param
-        ];
-        $result = $this->awxKlarna->checkSignature($data, 'secret');
-        if (!$result) {
-            @header("HTTP/1.0 400 Bad Request");
-            exit;
-        }
-        $notifyData = json_decode($param, true);
-        $orderNo = $notifyData['data']['object']['merchant_order_id'] ?: 0;
-        if (empty($orderNo)) {
-            @header("HTTP/1.0 400 Bad Request");
-            exit;
-        }
-        $prefix = $this->awxKlarna->getPrefix();
-        if (strpos($orderNo, $prefix) === false) {
-            @header("HTTP/1.0 200 ok");
-            exit;
+        request()->all();
+        $orderId = $event['resource']['invoice_id'];
+        $transactionId = $event['resource']['id'];
+        $type = $event['event_type'];
+        switch ($type) {
+            case 'PAYMENT.CAPTURE.COMPLETED':
+                $this->applepay->paymentSucceeded($orderId, $transactionId);
+                @header("HTTP/1.0 200 ok");
+                break;
+            default:
+                // 对于未知事件类型,记录日志但仍返回成功
+                @header("HTTP/1.0 200 ok");
+                break;
         }
-        $type = $notifyData['name'];
-        $orderId = str_replace($prefix, '', $orderNo);
-        $transactionId = $notifyData['data']['object']['id'] ?: '';
-        $eventType = "payments_webhook_" . strtolower(str_replace(".", "_", $type));
-        $this->awxKlarna->$eventType($orderId, $transactionId);
     }
 
 }

+ 52 - 5
packages/Longyi/Pay/Applepay/src/Payment/Applepay.php

@@ -4,6 +4,9 @@ namespace Longyi\Pay\Applepay\Payment;
 
 use GuzzleHttp\Client;
 use Webkul\Payment\Payment\Payment;
+use Webkul\Sales\Models\Order;
+use Webkul\Sales\Repositories\OrderRepository;
+use Webkul\Sales\Repositories\InvoiceRepository;
 
 class Applepay extends Payment
 {
@@ -26,7 +29,10 @@ class Applepay extends Payment
     public $orderTrackApi = 'https://api-m.sandbox.paypal.com/v2/checkout/orders/{id}/track';
     public $addTrackApi = 'https://api-m.sandbox.paypal.com/v1/shipping/trackers-batch';
 
-    public function __construct()
+    public function __construct(
+        protected InvoiceRepository $invoiceRepository,
+        protected OrderRepository $orderRepository,
+    )
     {
         if ($this->getConfigData('mode') == 'live') {
             $this->createOrderApi = 'https://api-m.paypal.com/v2/checkout/orders';
@@ -60,15 +66,16 @@ class Applepay extends Payment
     }
     public function createGatewayOrder()
     {
-        return $this->createOrder($this->getOrder());
+        return $this->createOrder($this->getOrder(), ['merchantOrderId' => $this->getOrder()->id]);
     }
-    public function createOrder($order)
+    public function createOrder($order, $override)
     {
         $billingAddressLines = $this->getAddressLines($order->billing_address->address);
         $data = [
-            'intent' => 'CAPTURE',
+            'intent' => 'AUTHORIZE',
             'purchase_units' => [
                 [
+                    'reference_id' => $override['merchantOrderId'],
                     'amount' => [
                         'currency_code' => $order->order_currency_code,
                         'value' => $this->formatCurrencyValue((float) $order->sub_total + $order->tax_total + ($order->selected_shipping_rate ? $order->selected_shipping_rate->price : 0) - $order->discount_amount),
@@ -113,7 +120,7 @@ class Applepay extends Payment
             'headers' => [
                 'Accept' => 'application/json',
                 'Content-Type' => 'application/json',
-                'Authorization' =>  'Bearer '.base64_encode("{$this->apikey}:{$this->secret}")
+                'Authorization' =>  'Basic '.base64_encode("{$this->apikey}:{$this->secret}")
             ],
             'json' => $data,
             'timeout' => 30,
@@ -147,6 +154,46 @@ class Applepay extends Payment
 
         return $lineItems;
     }
+
+    //成功修改状态
+    public function paymentSucceeded($orderId, $transactionId)
+    {
+        $order = $this->orderRepository->find($orderId);
+
+        if (!$order->id) {
+            return false;
+        }
+        if ($order->status != Order::STATUS_PENDING) {
+            return false;
+        }
+        $order->status = Order::STATUS_PROCESSING;
+        $order->save();
+        if ($order->payment) {
+            $additional = $order->payment->additional;
+            $additional['transaction_id'] = $transactionId;
+            $order->payment->additional = $additional;
+            $order->payment->save();
+        }
+        if ($order->canInvoice()) {
+            $this->invoiceRepository->create($this->prepareInvoiceData($order));
+        }
+    }
+    /**
+     * Prepares order's invoice data for creation.
+     */
+    protected function prepareInvoiceData($order): array
+    {
+        $invoiceData = [
+            'order_id' => $order->id,
+            'invoice'  => ['items' => []],
+        ];
+
+        foreach ($order->items as $item) {
+            $invoiceData['invoice']['items'][$item->id] = $item->qty_to_invoice;
+        }
+
+        return $invoiceData;
+    }
     protected function getAddressLines($address)
     {
         $address = explode(PHP_EOL, $address, 2);