Skip to content

Commit

Permalink
paa-399 graceful redirection
Browse files Browse the repository at this point in the history
  • Loading branch information
leon-zhang-awx committed Oct 31, 2024
1 parent 65e2891 commit b469bee
Show file tree
Hide file tree
Showing 22 changed files with 322 additions and 44 deletions.
31 changes: 19 additions & 12 deletions Helper/AvailablePaymentMethodsHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public function canInitialize(): bool
* @param string $code
*
* @return bool
* @throws GuzzleException|JsonException
* @throws JsonException|GuzzleException
*/
public function isAvailable(string $code): bool
{
Expand All @@ -92,28 +92,36 @@ public function isAvailable(string $code): bool
*/
private function getItems()
{
$items = $this->cache->load($this->getCacheName());
$cacheName = $this->getCacheName();
$items = $this->cache->load($cacheName);
if ($items) return json_decode($items, true);

$resp = $this->getLatestItems();
$this->cache->save(json_encode($resp), $this->getCacheName(), AbstractMethod::CACHE_TAGS, self::CACHE_TIME);
$this->cache->save(json_encode($resp), $cacheName, AbstractMethod::CACHE_TAGS, self::CACHE_TIME);
return $resp;
}

public function getLatestItems()
/**
* @throws GuzzleException
* @throws JsonException
*/
public function getLatestItems($useQuote = true)
{
return $this->availablePaymentMethod
->setCurrency($this->getCurrencyCode())
$request = $this->availablePaymentMethod
->setResources()
->setActive()
->setTransactionMode(AvailablePaymentMethods::TRANSACTION_MODE)
->send();
->setTransactionMode(AvailablePaymentMethods::TRANSACTION_MODE);
if ($useQuote) {
$request = $request->setCurrency($this->getCurrencyCode());
} else {
$request = $request->removeCurrency();
}
return $request->send();
}

/**
* @return array
* @throws GuzzleException
* @throws JsonException
* @throws JsonException|GuzzleException
*/
private function getAllMethods(): array
{
Expand All @@ -127,8 +135,7 @@ private function getAllMethods(): array

/**
* @return array
* @throws GuzzleException
* @throws JsonException
* @throws JsonException|GuzzleException
*/
public function getAllPaymentMethodTypes(): array
{
Expand Down
7 changes: 7 additions & 0 deletions Model/Client/AbstractClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,13 @@ protected function setParam(string $name, string $value): AbstractClient
return $this;
}

protected function unsetParam(string $name): AbstractClient
{
unset($this->params[$name]);

return $this;
}

/**
* @return string
*/
Expand Down
6 changes: 4 additions & 2 deletions Model/Client/Request/AvailablePaymentMethods.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

use Airwallex\Payments\Model\Client\AbstractClient;
use Airwallex\Payments\Model\Client\Interfaces\BearerAuthenticationInterface;
use JsonException;
use Psr\Http\Message\ResponseInterface;

class AvailablePaymentMethods extends AbstractClient implements BearerAuthenticationInterface
Expand All @@ -20,9 +19,12 @@ class AvailablePaymentMethods extends AbstractClient implements BearerAuthentica
*/
public function setCurrency(string $currency): self
{
if (empty($currency)) return $this;
return $this->setParam('transaction_currency', $currency);
}
public function removeCurrency(): self
{
return $this->unsetParam('transaction_currency');
}

public function setResources(): self
{
Expand Down
44 changes: 39 additions & 5 deletions Model/Client/Request/PaymentIntents/Confirm.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

use Airwallex\Payments\Model\Client\AbstractClient;
use Airwallex\Payments\Model\Client\Interfaces\BearerAuthenticationInterface;
use Airwallex\Payments\Model\Methods\KlarnaMethod;
use JsonException;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Psr\Http\Message\ResponseInterface;

class Confirm extends AbstractClient implements BearerAuthenticationInterface
Expand All @@ -30,25 +32,57 @@ public function setPaymentIntentId(string $id): self
return $this;
}

private function getLanguageCode($countryCode): string
{
if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) return 'en';
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$lang = $languages[0];
if ($lang === 'zh-TW') {
$lang = 'zh-HK';
}
if (in_array($lang, KlarnaMethod::COUNTRY_LANGUAGE[$countryCode], true)) {
return $lang;
}
return 'en';
}

/**
* @param string $method
*
* @param OrderAddressInterface|null $address
* @return Confirm
*/
public function setInformation(string $method): self
public function setInformation(string $method, OrderAddressInterface $address = null): self
{
$data = [
'type' => $method
'type' => $method,
];

if ($method !== 'pay_now') {
if ($method === 'klarna') {
$countryCode = $address->getCountryId();
$data['klarna'] = [
'country_code' => $countryCode,
'billing' => [
'address' => [
"country_code" => $countryCode,
"street" => $address->getStreet() ? implode(', ', $address->getStreet()) : '',
"city" => $address->getCity(),
'state' => $address->getRegionCode(),
'postcode' => $address->getPostcode(),
],
'email' => $address->getEmail(),
'first_name' => $address->getFirstName(),
'last_name' => $address->getLastname(),
],
'language' => $this->getLanguageCode($countryCode),
];
} else if ($method !== 'pay_now') {
$data[$method] = [
'flow' => 'qrcode'
];
}

return $this->setParams([
'payment_method' => $data
'payment_method' => $data,
]);
}

Expand Down
2 changes: 1 addition & 1 deletion Model/Client/Request/PaymentIntents/Create.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public function setOrder(Order $order, string $returnUrl): self
'amount' => $order->getGrandTotal(),
'currency' => $order->getOrderCurrencyCode(),
'merchant_order_id' => $order->getIncrementId(),
'return_url' => $returnUrl,
'return_url' => trim($returnUrl, '/'),
'order' => [
'products' => $this->getProducts($order),
'shipping' => $this->getShippingAddress($order)
Expand Down
66 changes: 66 additions & 0 deletions Model/Methods/KlarnaMethod.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Airwallex\Payments\Model\Methods;

use Magento\Quote\Api\Data\CartInterface;

class KlarnaMethod extends CardMethod
{
public const CODE = 'airwallex_payments_klarna';

const SUPPORTED_COUNTRY_TO_CURRENCY = [
'AT' => 'EUR',
'BE' => 'EUR',
'FI' => 'EUR',
'FR' => 'EUR',
'DE' => 'EUR',
'GR' => 'EUR',
'IE' => 'EUR',
'IT' => 'EUR',
'NL' => 'EUR',
'PT' => 'EUR',
'ES' => 'EUR',
'DK' => 'DKK',
'NO' => 'NOK',
'PL' => 'PLN',
'SE' => 'SEK',
'CH' => 'CHF',
'GB' => 'GBP',
'CZ' => 'CZK',
'US' => 'USD',
];

const COUNTRY_LANGUAGE = [
'AT' => ['de'],
'BE' => ['be', 'nl', 'fr'],
'CA' => ['fr'],
'CH' => ['it', 'de', 'fr'],
'CZ' => ['cs'],
'DE' => ['de'],
'DK' => ['da'],
'ES' => ['es', 'ca'],
'FI' => ['fi', 'sv'],
'FR' => ['fr'],
'GR' => ['el'],
'IT' => ['it'],
'NL' => ['nl'],
'NO' => ['nb'],
'PL' => ['pl'],
'PT' => ['pt'],
'SE' => ['sv'],
'US' => ['es'],
];

public function isAvailable(CartInterface $quote = null): bool
{
$codes = $this->availablePaymentMethodsHelper->getLatestItems(false);
$code = $this->getPaymentMethodCode($this->getCode());
foreach ($codes as $codeItem) {
if (!empty($codeItem['name']) && $codeItem['name'] === $code) {
return true;
}
}

return false;
}
}
5 changes: 1 addition & 4 deletions Model/Methods/RedirectMethod.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@

namespace Airwallex\Payments\Model\Methods;

use GuzzleHttp\Exception\GuzzleException;
use JsonException;
use Magento\Quote\Api\Data\CartInterface;

class RedirectMethod extends AbstractMethod
{
public const DANA_CODE = 'airwallex_payments_dana';
Expand All @@ -16,4 +12,5 @@ class RedirectMethod extends AbstractMethod
public const TOUCH_N_GO_CODE = 'airwallex_payments_tng';
public const WECHAT_CODE = 'airwallex_payments_wechatpay';
public const PAY_NOW_CODE = 'airwallex_payments_pay_now';
public const KLARNA_CODE = 'airwallex_payments_klarna';
}
12 changes: 6 additions & 6 deletions Model/OrderService.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
use Magento\Quote\Api\CartRepositoryInterface;
use Magento\Quote\Api\Data\PaymentInterface;
use Magento\Quote\Model\Quote;
use Magento\Sales\Api\Data\OrderAddressInterface;
use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Model\Order;
use Airwallex\Payments\Model\Client\Request\PaymentIntents\Get;
Expand Down Expand Up @@ -312,7 +313,7 @@ public function orderThenIntent(Quote $quote, $uid, string $cartId, PaymentInter
'client_secret' => $intent['clientSecret']
];
if ($this->isRedirectMethodConstant($paymentMethod->getMethod())) {
$data['next_action'] = $this->getAirwallexPaymentsNextAction($intent['id'], $paymentMethod->getMethod());
$data['next_action'] = $this->getAirwallexPaymentsNextAction($intent['id'], $paymentMethod->getMethod(), $order->getBillingAddress());
}

$this->cache->save(1, $this->reCaptchaValidationPlugin->getCacheKey($intent['id']), [], 3600);
Expand Down Expand Up @@ -363,6 +364,7 @@ public function isOrderEqualToQuote(Order $order, Quote $quote, ?AddressInterfac
if ($quoteAddr && !$orderAddr) return false;
if (!$quoteAddr && $orderAddr) return false;
if ($quoteAddr && $orderAddr) {
/* @var OrderAddress $orderAddr */
if (!$this->isQuoteAddressSameAsOrderAddress($quoteAddr, $orderAddr)) return false;
}

Expand Down Expand Up @@ -394,18 +396,16 @@ public function isQuoteAddressSameAsOrderAddress(Address $quoteAddr, OrderAddres
* @throws LocalizedException
* @throws Exception
*/
public function getAirwallexPaymentsNextAction(string $intentId, $code)
public function getAirwallexPaymentsNextAction(string $intentId, $code, OrderAddressInterface $address)
{
if (!$intentId) {
throw new Exception('Intent id is required.');
}
$cacheName = $code . '-qrcode-' . $intentId;
if (!$returnUrl = $this->cache->load($cacheName)) {
try {
$resp = $this->confirm
->setPaymentIntentId($intentId)
->setInformation($this->getPaymentMethodCode($code))
->send();
$request = $this->confirm->setPaymentIntentId($intentId);
$resp = $request->setInformation($this->getPaymentMethodCode($code), $address)->send();
} catch (Exception $exception) {
throw new LocalizedException(__($exception->getMessage()));
}
Expand Down
16 changes: 7 additions & 9 deletions Model/PaymentIntents.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
use Airwallex\Payments\Model\Traits\HelperTrait;
use GuzzleHttp\Exception\GuzzleException;
use Magento\Checkout\Model\Session;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Exception\AlreadyExistsException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\UrlInterface;
Expand Down Expand Up @@ -73,14 +72,13 @@ public function __construct(
*/
public function createIntentByOrder(Order $order, string $phone, string $email, string $from): array
{
$uid = $order->getCustomerId() ?: 0;
if ($uid && $this->isMiniPluginExists()) {
$uid = ObjectManager::getInstance()->get(CompanyConsentsInterface::class)->getSuperId($uid);
}
$airwallexCustomerId = $this->paymentConsents->getAirwallexCustomerIdInDB($uid);

$create = $this->paymentIntentsCreate->setOrder($order, $this->urlInterface->getUrl('checkout/onepage/success'));
// $create = $from === 'card_with_saved' ? $create->setAirwallexCustomerId($airwallexCustomerId) : $create->setCustomer($email, $phone);
// $uid = $order->getCustomerId() ?: 0;
// if ($uid && $this->isMiniPluginExists()) {
// $uid = ObjectManager::getInstance()->get(CompanyConsentsInterface::class)->getSuperId($uid);
// }
// $airwallexCustomerId = $this->paymentConsents->getAirwallexCustomerIdInDB($uid);
// $create = $from === 'card_with_saved' ? $create->setAirwallexCustomerId($airwallexCustomerId) : $create->setCustomer($email, $phone);
$create = $this->paymentIntentsCreate->setOrder($order, $this->urlInterface->getUrl('checkout#payment'));
$intent = $create->setCustomer($email, $phone)->send();

$products = $this->getProducts($order);
Expand Down
10 changes: 9 additions & 1 deletion Model/Traits/HelperTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ public function getShippingAddress($object): ?array
'last_name' => $shippingAddress->getLastname(),
'phone_number' => $shippingAddress->getTelephone(),
'shipping_method' => $method,
'fee_amount' => $object->getShippingAmount(),
'address' => [
'city' => $shippingAddress->getCity(),
'country_code' => $shippingAddress->getCountryId(),
Expand Down Expand Up @@ -141,6 +142,13 @@ public function getProducts($object): array
'type' => $product ? $product->getTypeId() : '',
];
}
$products[] = [
'code' => 0,
'name' => 'fake-product',
'quantity' => 1,
'sku' => 'fake-product',
'unit_price' => $object->getGrandTotal(),
];
return $products;
}

Expand All @@ -163,7 +171,7 @@ public function getBillingAddress($object): ?array
'postcode' => $billingAddress->getPostcode(),
'state' => $billingAddress->getRegion(),
'street' => implode(', ', $billingAddress->getStreet()),
]
],
];
}

Expand Down
2 changes: 2 additions & 0 deletions Model/Ui/ConfigProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Airwallex\Payments\Api\PaymentConsentsInterface;
use Airwallex\Payments\Helper\Configuration;
use Airwallex\Payments\Model\Methods\KlarnaMethod;
use GuzzleHttp\Exception\GuzzleException;
use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Customer\Model\Session;
Expand Down Expand Up @@ -87,6 +88,7 @@ public function getConfig(): array
'is_pre_verification_enabled' => $this->configuration->isPreVerificationEnabled(),
'card_max_width' => $this->configuration->getCardMaxWidth(),
'card_fontsize' => $this->configuration->getCardFontSize(),
'klarna_support_countries' => KlarnaMethod::SUPPORTED_COUNTRY_TO_CURRENCY,
]
]
];
Expand Down
Loading

0 comments on commit b469bee

Please sign in to comment.