get("payment"); } public function initiatePay(Payment $payment, Request $request = null) { $result = new ServiceResult(); $returnUrl = (string)($request ? $request->get("return_url") : ""); $cancelUrl = (string)($request ? $request->get("cancel_url") : ""); if ($returnUrl === "" || $cancelUrl === "") { $result->addError(new Error("PayPal return addresses are missing")); return $result; } $amount = $this->amount($payment); if ($amount === null) { $result->addError(new Error("PayPal exchange rate is not set")); return $result; } [$currency, $value] = $amount; $order = $payment->getOrder(); $response = $this->call( $payment, "POST", "/v2/checkout/orders", [ "intent" => "CAPTURE", "purchase_units" => [[ "reference_id" => (string)$payment->getId(), "custom_id" => (string)$order->getField("ACCOUNT_NUMBER"), "description" => (string)$order->getField("ACCOUNT_NUMBER"), "amount" => ["currency_code" => $currency, "value" => $value], ]], "payment_source" => ["paypal" => ["experience_context" => [ "brand_name" => (string)$this->getBusinessValue($payment, "PAYPAL_BRAND"), "shipping_preference" => "NO_SHIPPING", "user_action" => "PAY_NOW", "return_url" => $returnUrl, "cancel_url" => $cancelUrl, ]]], ], "create-" . $payment->getId() . "-" . $value . "-" . time() ); if (isset($response["error"])) { $result->addError(new Error($response["error"])); return $result; } $link = ""; foreach ((array)($response["links"] ?? []) as $item) { if (in_array($item["rel"] ?? "", ["payer-action", "approve"], true)) { $link = (string)$item["href"]; break; } } if ($link === "" || empty($response["id"])) { $result->addError(new Error("PayPal did not return an approval address")); return $result; } $payment->setField("PS_INVOICE_ID", (string)$response["id"]); $payment->setField("PS_SUM", (float)$value); $payment->setField("PS_CURRENCY", $currency); $result->setPaymentUrl($link); return $result; } public function processRequest(Payment $payment, Request $request) { $result = new ServiceResult(); if ($payment->isPaid()) { return $result; } $token = (string)$request->get("token"); if ($token === "" || $token !== (string)$payment->getField("PS_INVOICE_ID")) { $result->addError(new Error("PayPal order does not match the payment")); return $result; } $currency = (string)$payment->getField("PS_CURRENCY"); $expected = (float)$payment->getField("PS_SUM"); if ($currency === "" || $expected <= 0) { $result->addError(new Error("PayPal payment was not started")); return $result; } $response = $this->call($payment, "GET", "/v2/checkout/orders/" . rawurlencode($token)); if (isset($response["error"])) { $result->addError(new Error($response["error"])); return $result; } if (($response["status"] ?? "") === "APPROVED") { $unit = $response["purchase_units"][0]["amount"] ?? []; if (($unit["currency_code"] ?? "") !== $currency || abs((float)($unit["value"] ?? 0) - $expected) > 0.01) { $result->addError(new Error("PayPal amount does not match the order")); return $result; } $response = $this->call($payment, "POST", "/v2/checkout/orders/" . rawurlencode($token) . "/capture", new \stdClass(), "capture-" . $token); if (isset($response["error"]) && ($response["issue"] ?? "") === "ORDER_ALREADY_CAPTURED") { $response = $this->call($payment, "GET", "/v2/checkout/orders/" . rawurlencode($token)); } if (isset($response["error"])) { $result->addError(new Error($response["error"])); return $result; } } $capture = $response["purchase_units"][0]["payments"]["captures"][0] ?? null; if (($response["status"] ?? "") !== "COMPLETED" || !is_array($capture) || ($capture["status"] ?? "") !== "COMPLETED") { $result->addError(new Error("PayPal payment is not completed: " . (string)($response["status"] ?? ""))); return $result; } if (($capture["amount"]["currency_code"] ?? "") !== $currency || abs((float)($capture["amount"]["value"] ?? 0) - $expected) > 0.01) { $result->addError(new Error("PayPal amount does not match the order")); return $result; } $result->setPsData([ "PS_INVOICE_ID" => $token, "PS_STATUS" => "Y", "PS_STATUS_CODE" => (string)$capture["status"], "PS_STATUS_DESCRIPTION" => "PayPal capture " . (string)($capture["id"] ?? ""), "PS_SUM" => $expected, "PS_CURRENCY" => $currency, "PS_RESPONSE_DATE" => new DateTime(), ]); $result->setOperationType(ServiceResult::MONEY_COMING); return $result; } private function amount(Payment $payment): ?array { $sum = PriceMaths::roundByFormatCurrency($payment->getSum(), $payment->getCurrency()); $currency = trim((string)$this->getBusinessValue($payment, "PAYPAL_CURRENCY")); if ($currency === "" || $currency === $payment->getCurrency()) { return [$payment->getCurrency(), number_format($sum, 2, ".", "")]; } $rate = (float)str_replace(",", ".", (string)$this->getBusinessValue($payment, "PAYPAL_RATE")); if ($rate <= 0) { return null; } return [$currency, number_format($sum / $rate, 2, ".", "")]; } private function base(Payment $payment): string { return $this->getBusinessValue($payment, "PAYPAL_TEST") === "N" ? self::LIVE : self::SANDBOX; } private function token(Payment $payment): ?string { if ($this->accessToken !== null) { return $this->accessToken; } $client = new HttpClient(["socketTimeout" => 15, "streamTimeout" => 25]); $client->setAuthorization((string)$this->getBusinessValue($payment, "PAYPAL_CLIENT_ID"), (string)$this->getBusinessValue($payment, "PAYPAL_SECRET")); $client->setHeader("Content-Type", "application/x-www-form-urlencoded"); $body = $client->post($this->base($payment) . "/v1/oauth2/token", "grant_type=client_credentials"); $data = is_string($body) && $body !== "" ? json_decode($body, true) : null; if (!is_array($data) || empty($data["access_token"])) { PaySystem\Logger::addError(__CLASS__ . ": token request failed, HTTP " . $client->getStatus()); return null; } return $this->accessToken = (string)$data["access_token"]; } private function call(Payment $payment, string $method, string $path, mixed $payload = null, string $requestId = ""): array { $token = $this->token($payment); if ($token === null) { return ["error" => "PayPal authorization failed"]; } $client = new HttpClient(["socketTimeout" => 15, "streamTimeout" => 30]); $client->setHeader("Authorization", "Bearer " . $token); $client->setHeader("Content-Type", "application/json"); if ($requestId !== "") { $client->setHeader("PayPal-Request-Id", $requestId); } $url = $this->base($payment) . $path; $body = $method === "GET" ? $client->get($url) : $client->post($url, Json::encode($payload)); $status = $client->getStatus(); $data = is_string($body) && $body !== "" ? json_decode($body, true) : []; $data = is_array($data) ? $data : []; if ($status < 200 || $status >= 300) { $issue = (string)($data["details"][0]["issue"] ?? $data["name"] ?? ""); PaySystem\Logger::addError(__CLASS__ . ": " . $method . " " . $path . " HTTP " . $status . " " . $issue); return ["error" => "PayPal HTTP " . $status . " " . $issue, "issue" => $issue]; } return $data; } }