|
|
@@ -0,0 +1,496 @@
|
|
|
+<?php
|
|
|
+
|
|
|
+namespace common\services;
|
|
|
+
|
|
|
+use common\helpers\GuestDeclarationDraftStatus;
|
|
|
+use common\helpers\Cache;
|
|
|
+use common\helpers\Form;
|
|
|
+use common\helpers\user\Info;
|
|
|
+use common\models\Countries;
|
|
|
+use common\models\Currency;
|
|
|
+use common\models\GuestDeclarationDraft;
|
|
|
+use common\models\ApproachOrder;
|
|
|
+use common\models\DeclarationPackage;
|
|
|
+use common\models\ShopGoods;
|
|
|
+use common\models\ShopGoodsNature;
|
|
|
+use common\models\Region;
|
|
|
+use common\models\forms\ApproachDeclarationForm;
|
|
|
+use common\models\forms\ApproachDeclarationLoopForm;
|
|
|
+use common\models\forms\ApproachOrderForm;
|
|
|
+use common\models\User;
|
|
|
+use common\models\UserNetwork;
|
|
|
+use common\models\UserRelation;
|
|
|
+use Yii;
|
|
|
+use yii\web\BadRequestHttpException;
|
|
|
+use yii\web\NotFoundHttpException;
|
|
|
+
|
|
|
+/** Handles the public, pre-payment part of a guest registration order. */
|
|
|
+class GuestDeclarationOrderService
|
|
|
+{
|
|
|
+ private const DRAFT_TTL = 86400;
|
|
|
+
|
|
|
+ public function createDraft(string $countryId): array
|
|
|
+ {
|
|
|
+ $country = Countries::getById($countryId);
|
|
|
+ if (!$country || empty($country['ACTIVE'])) {
|
|
|
+ throw new BadRequestHttpException('Unsupported country.');
|
|
|
+ }
|
|
|
+ $currency = Currency::getById((string) $country['LOCAL_CURRENCY_ID']);
|
|
|
+ if (!$currency || empty($currency['ACTIVE']) || empty($currency['CODE'])) {
|
|
|
+ throw new BadRequestHttpException('Payment currency is unavailable.');
|
|
|
+ }
|
|
|
+
|
|
|
+ $token = Yii::$app->security->generateRandomString(64);
|
|
|
+ $username = Info::generateWebName($countryId);
|
|
|
+ if (!$username) {
|
|
|
+ throw new \RuntimeException('Unable to generate a member number.');
|
|
|
+ }
|
|
|
+ $draft = new GuestDeclarationDraft();
|
|
|
+ $draft->ID = Yii::$app->security->generateRandomString(32);
|
|
|
+ $draft->ORDER_SN = 'OS' . strtoupper(bin2hex(random_bytes(12)));
|
|
|
+ $draft->ACCESS_TOKEN_HASH = hash('sha256', $token);
|
|
|
+ $draft->STATUS = GuestDeclarationDraftStatus::DRAFT;
|
|
|
+ $draft->PAYLOAD = '{}';
|
|
|
+ $draft->ORDER_SNAPSHOT = '{}';
|
|
|
+ $draft->PAY_AMOUNT = 0;
|
|
|
+ $draft->CURRENCY = strtoupper($currency['CODE']);
|
|
|
+ $draft->CREATED_AT = time();
|
|
|
+ $draft->EXPIRES_AT = time() + self::DRAFT_TTL;
|
|
|
+
|
|
|
+ // This is a proposal only. The number is checked again before payment completion.
|
|
|
+ $draft->USER_ID = null;
|
|
|
+ $draft->PAYLOAD = json_encode([
|
|
|
+ 'countryId' => $countryId,
|
|
|
+ 'insertUserName' => $username,
|
|
|
+ ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
|
+ if (!$draft->save()) {
|
|
|
+ throw new \RuntimeException('Unable to create guest order draft.');
|
|
|
+ }
|
|
|
+ if (!Yii::$app->redis->setnx('key_' . $username, $username)) {
|
|
|
+ $draft->delete();
|
|
|
+ throw new \RuntimeException('Unable to reserve a unique member number. Please retry.');
|
|
|
+ }
|
|
|
+ Yii::$app->redis->expire('key_' . $username, self::DRAFT_TTL + 600);
|
|
|
+
|
|
|
+ return [
|
|
|
+ 'draftId' => $draft->ID,
|
|
|
+ 'accessToken' => $token,
|
|
|
+ 'insertUserName' => $username,
|
|
|
+ 'expiresAt' => (int) $draft->EXPIRES_AT,
|
|
|
+ 'currency' => $draft->CURRENCY,
|
|
|
+ ];
|
|
|
+ }
|
|
|
+
|
|
|
+ public function getDraftStatus(string $draftId, string $accessToken): array
|
|
|
+ {
|
|
|
+ $draft = $this->loadAuthorizedDraft($draftId, $accessToken);
|
|
|
+ if ($draft->STATUS === GuestDeclarationDraftStatus::PAYMENT_INITIALIZING && (int) $draft->UPDATED_AT < time() - 900) {
|
|
|
+ $draft->transitionTo(GuestDeclarationDraftStatus::MANUAL_REVIEW);
|
|
|
+ } elseif ($draft->isExpired() && in_array($draft->STATUS, [GuestDeclarationDraftStatus::DRAFT, GuestDeclarationDraftStatus::PENDING_PAYMENT], true)) {
|
|
|
+ $draft->transitionTo(GuestDeclarationDraftStatus::EXPIRED);
|
|
|
+ }
|
|
|
+
|
|
|
+ return [
|
|
|
+ 'status' => $draft->STATUS,
|
|
|
+ 'orderSn' => $draft->STATUS === GuestDeclarationDraftStatus::COMPLETED ? $draft->ORDER_SN : null,
|
|
|
+ 'userName' => $draft->STATUS === GuestDeclarationDraftStatus::COMPLETED ? ($draft->getPayload()['insertUserName'] ?? null) : null,
|
|
|
+ ];
|
|
|
+ }
|
|
|
+
|
|
|
+ public function submitDraft(string $draftId, string $accessToken, array $input): array
|
|
|
+ {
|
|
|
+ $draft = $this->loadAuthorizedDraft($draftId, $accessToken);
|
|
|
+ if ($draft->isExpired()) {
|
|
|
+ $draft->transitionTo(GuestDeclarationDraftStatus::EXPIRED);
|
|
|
+ throw new BadRequestHttpException('Guest order draft has expired.');
|
|
|
+ }
|
|
|
+ if ($draft->STATUS === GuestDeclarationDraftStatus::PENDING_PAYMENT) {
|
|
|
+ return $this->paymentResponse($draft);
|
|
|
+ }
|
|
|
+ if ($draft->STATUS === GuestDeclarationDraftStatus::PAYMENT_INITIALIZING) {
|
|
|
+ throw new BadRequestHttpException('Payment initialization is in progress.');
|
|
|
+ }
|
|
|
+ if (!in_array($draft->STATUS, [GuestDeclarationDraftStatus::DRAFT, GuestDeclarationDraftStatus::PAYMENT_FAILED], true)) {
|
|
|
+ throw new BadRequestHttpException('Guest order draft cannot be submitted in its current state.');
|
|
|
+ }
|
|
|
+
|
|
|
+ foreach (['amount', 'payAmount', 'currency', 'pv', 'exchangeRate', 'goodsTitle', 'price', 'realPrice'] as $untrustedField) {
|
|
|
+ if (array_key_exists($untrustedField, $input)) {
|
|
|
+ throw new BadRequestHttpException('Price and product fields are calculated by the server.');
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ $payload = $draft->getPayload();
|
|
|
+ $countryId = (string) ($payload['countryId'] ?? '');
|
|
|
+ unset($input['draftId'], $input['accessToken'], $input['allData'], $input['isGuestDeclaration'], $input['guestOrderSn'], $input['_insertUserId']);
|
|
|
+ $input['insertUserName'] = $payload['insertUserName'] ?? '';
|
|
|
+ $input['countryId'] = $countryId;
|
|
|
+ $input['goodsId'] = $input['goodsId'] ?? [];
|
|
|
+ $input['goodsNum'] = $input['goodsNum'] ?? [];
|
|
|
+ $input['type'] = ApproachDeclarationForm::TYPE_ZC;
|
|
|
+ $input['payType'] = 'pay_stack';
|
|
|
+ $input['province'] = !empty($input['province']) ? $input['province'] : 1;
|
|
|
+ $input['city'] = !empty($input['city']) ? $input['city'] : 1;
|
|
|
+ $input['county'] = !empty($input['county']) ? $input['county'] : 1;
|
|
|
+ $referrerName = trim((string) ($input['conUserName'] ?? ''));
|
|
|
+ $sponsorName = trim((string) ($input['recUserName'] ?? ''));
|
|
|
+ $referrerId = Info::getUserIdByUserName($referrerName);
|
|
|
+ $sponsorId = Info::getUserIdByUserName($sponsorName);
|
|
|
+ $relation = $referrerId ? UserRelation::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $referrerId]) : null;
|
|
|
+ $parentIds = $relation ? array_map('strval', explode(',', (string) $relation['PARENT_UIDS'])) : [];
|
|
|
+ if (!$referrerId || !$sponsorId || ((string) $sponsorId !== (string) $referrerId && !in_array((string) $sponsorId, $parentIds, true))) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'fillSponsorUpline'));
|
|
|
+ }
|
|
|
+ $stockistName = trim((string) ($input['decUserName'] ?? ''));
|
|
|
+ if ($stockistName === '' || !User::find()->where(['USER_NAME' => $stockistName, 'IS_DEC' => 1])->exists()) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'stockistDoesNotExist'));
|
|
|
+ }
|
|
|
+ if ((string) $input['province'] !== '1' && !Region::getWarehouseByCode($input['province'])) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'deliveryTemporarilyNotSupported'));
|
|
|
+ }
|
|
|
+ $bottomPlace = UserNetwork::getBottomPlace($referrerId, '', 'left');
|
|
|
+ $bottom = UserNetwork::find()->select('USER_ID')->where(['LOCATION_TAG' => $bottomPlace])->asArray()->one();
|
|
|
+ $bottomUser = $bottom ? User::findOneAsArray(['ID' => $bottom['USER_ID']], 'USER_NAME') : null;
|
|
|
+ if (!$bottomUser) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'stockistDoesNotExist'));
|
|
|
+ }
|
|
|
+ $input['conUserName'] = $bottomUser['USER_NAME'];
|
|
|
+ $input['recUserName'] = $referrerName;
|
|
|
+ $input['bottomUserName'] = $sponsorName;
|
|
|
+ $input['location'] = 1;
|
|
|
+
|
|
|
+ $form = new ApproachDeclarationForm();
|
|
|
+ $form->scenario = 'userDec';
|
|
|
+ foreach ($input as $name => $value) {
|
|
|
+ if (in_array($name, $form->safeAttributes(), true) && $name !== 'allData') {
|
|
|
+ $form->$name = $value;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ $form->bottomUserName = $sponsorName;
|
|
|
+ $allowedInput = array_flip(array_merge($form->safeAttributes(), ['bottomUserName', 'payType', 'countryId']));
|
|
|
+ unset($allowedInput['allData']);
|
|
|
+ $input = array_intersect_key($input, $allowedInput);
|
|
|
+ $form->allData = [$input];
|
|
|
+ if (!$form->validate()) {
|
|
|
+ throw new BadRequestHttpException(Form::formatErrorsForApi($form->getErrors()));
|
|
|
+ }
|
|
|
+ if (User::find()->where(['USER_NAME' => $input['insertUserName']])->exists()
|
|
|
+ || Yii::$app->redis->get('key_' . $input['insertUserName']) !== $input['insertUserName']
|
|
|
+ ) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'memberNumberExpired'));
|
|
|
+ }
|
|
|
+
|
|
|
+ [$amount, $pv, $goods] = $this->quote($input);
|
|
|
+ $levels = Cache::getDecLevelConfig();
|
|
|
+ $minimumPv = $levels ? min(array_map(static function ($level) { return (float) $level['PERF']; }, $levels)) : 0;
|
|
|
+ if ($pv < $minimumPv) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanSelectedBV'));
|
|
|
+ }
|
|
|
+ if ((string) ($input['decWay'] ?? '') !== '1') {
|
|
|
+ $selectedLevel = $levels[$input['decLv'] ?? ''] ?? null;
|
|
|
+ if (!$selectedLevel) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'pleaseSelectTheEntryLevel'));
|
|
|
+ }
|
|
|
+ if ($pv < (float) $selectedLevel['PERF']) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanSelectedBV'));
|
|
|
+ }
|
|
|
+ $actualLevel = null;
|
|
|
+ foreach ($levels as $levelId => $level) {
|
|
|
+ if ($pv >= (float) $level['PERF']) {
|
|
|
+ $actualLevel = $levelId;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if ($actualLevel !== null && (string) $input['decLv'] !== (string) $actualLevel) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanNextSelectedLevelBV'));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if ($amount <= 0 || empty($input['email']) || !filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
|
|
|
+ throw new BadRequestHttpException('A valid payment email and positive order amount are required.');
|
|
|
+ }
|
|
|
+ $country = Countries::getById($countryId);
|
|
|
+ $currency = Currency::getById((string) $country['LOCAL_CURRENCY_ID']);
|
|
|
+ $orderSn = $draft->ORDER_SN;
|
|
|
+ $input['password'] = Yii::$app->security->generatePasswordHash((string) $input['password']);
|
|
|
+ $input['payPassword'] = Yii::$app->security->generatePasswordHash((string) $input['payPassword']);
|
|
|
+ $storedPayload = json_encode($input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
|
+ $reserved = GuestDeclarationDraft::updateAll(
|
|
|
+ ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_INITIALIZING, 'UPDATED_AT' => time()],
|
|
|
+ ['AND', ['ID' => $draft->ID], ['STATUS' => $draft->STATUS], ['>' , 'EXPIRES_AT', time()]]
|
|
|
+ );
|
|
|
+ if ($reserved !== 1) {
|
|
|
+ $draft->refresh();
|
|
|
+ if ($draft->STATUS === GuestDeclarationDraftStatus::PENDING_PAYMENT) {
|
|
|
+ return $this->paymentResponse($draft);
|
|
|
+ }
|
|
|
+ throw new BadRequestHttpException('Guest order draft is already being submitted.');
|
|
|
+ }
|
|
|
+ $paymentReference = 'GD' . strtoupper(bin2hex(random_bytes(12)));
|
|
|
+ $init = \common\helpers\PayStack::transactionInit(
|
|
|
+ strtoupper($currency['CODE']),
|
|
|
+ $amount,
|
|
|
+ $input['email'],
|
|
|
+ ['custom_fields' => [
|
|
|
+ ['display_name' => 'Order SN', 'variable_name' => 'orderSn', 'value' => $orderSn],
|
|
|
+ ['display_name' => 'Order Type', 'variable_name' => 'orderType', 'value' => 'guestUserDec'],
|
|
|
+ ]],
|
|
|
+ $paymentReference
|
|
|
+ );
|
|
|
+ if (empty($init['status']) || empty($init['data']['reference']) || empty($init['data']['authorization_url'])) {
|
|
|
+ GuestDeclarationDraft::updateAll(
|
|
|
+ ['STATUS' => GuestDeclarationDraftStatus::DRAFT, 'UPDATED_AT' => time()],
|
|
|
+ ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_INITIALIZING]]
|
|
|
+ );
|
|
|
+ throw new \RuntimeException('Unable to initialize payment. Please retry.');
|
|
|
+ }
|
|
|
+
|
|
|
+ $draft->PAYLOAD = $storedPayload;
|
|
|
+ $draft->ORDER_SNAPSHOT = json_encode(['amount' => $amount, 'pv' => $pv, 'goods' => $goods], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
|
|
|
+ $draft->PAY_AMOUNT = $amount;
|
|
|
+ $draft->CURRENCY = strtoupper($currency['CODE']);
|
|
|
+ $draft->PAYMENT_REFERENCE = $init['data']['reference'];
|
|
|
+ $draft->PAYMENT_NOTE = json_encode([
|
|
|
+ 'authorization_url' => $init['data']['authorization_url'],
|
|
|
+ 'access_code' => $init['data']['access_code'] ?? null,
|
|
|
+ ]);
|
|
|
+ $draft->STATUS = GuestDeclarationDraftStatus::PENDING_PAYMENT;
|
|
|
+ $draft->UPDATED_AT = time();
|
|
|
+ if (!$draft->save(false)) {
|
|
|
+ GuestDeclarationDraft::updateAll([
|
|
|
+ 'STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW,
|
|
|
+ 'PAYLOAD' => $draft->PAYLOAD,
|
|
|
+ 'ORDER_SNAPSHOT' => $draft->ORDER_SNAPSHOT,
|
|
|
+ 'PAY_AMOUNT' => $draft->PAY_AMOUNT,
|
|
|
+ 'CURRENCY' => $draft->CURRENCY,
|
|
|
+ 'PAYMENT_REFERENCE' => $draft->PAYMENT_REFERENCE,
|
|
|
+ 'PAYMENT_NOTE' => $draft->PAYMENT_NOTE,
|
|
|
+ 'UPDATED_AT' => time(),
|
|
|
+ ], ['ID' => $draft->ID]);
|
|
|
+ throw new \RuntimeException('Payment started but its draft could not be saved; manual review is required.');
|
|
|
+ }
|
|
|
+ return $this->paymentResponse($draft);
|
|
|
+ }
|
|
|
+
|
|
|
+ private function paymentResponse(GuestDeclarationDraft $draft): array
|
|
|
+ {
|
|
|
+ $payment = json_decode((string) $draft->PAYMENT_NOTE, true) ?: [];
|
|
|
+ return [
|
|
|
+ 'orderSn' => $draft->ORDER_SN,
|
|
|
+ 'amount' => (float) $draft->PAY_AMOUNT,
|
|
|
+ 'currency' => $draft->CURRENCY,
|
|
|
+ 'reference' => $draft->PAYMENT_REFERENCE,
|
|
|
+ 'authorizationUrl' => $payment['authorization_url'] ?? null,
|
|
|
+ 'accessCode' => $payment['access_code'] ?? null,
|
|
|
+ ];
|
|
|
+ }
|
|
|
+
|
|
|
+ private function quote(array $input): array
|
|
|
+ {
|
|
|
+ $goods = [];
|
|
|
+ $amount = 0.0;
|
|
|
+ $pv = 0.0;
|
|
|
+ if (!empty($input['decWay']) && (string) $input['decWay'] === '1') {
|
|
|
+ $package = DeclarationPackage::findOneAsArray('ID=:ID AND STATUS=1', [':ID' => $input['packageId'] ?? null]);
|
|
|
+ if (!$package || (int) $package['STORE_NUMS'] <= 0) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'productsDoesSoldOut'));
|
|
|
+ }
|
|
|
+ if ((string) ($input['decLv'] ?? '') !== (string) $package['LEVEL_ID']) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'pleaseSelectTheEntryLevel'));
|
|
|
+ }
|
|
|
+ $amount = (float) $package['AMOUNT'];
|
|
|
+ $pv = (float) $package['PV'];
|
|
|
+ $goods[] = ['GOODS_ID' => $package['ID'], 'PRICE' => $amount, 'PV' => $pv, 'BUY_NUMS' => 1, 'SKU_CODE' => $package['PACKAGE_NO'], 'GOODS_TITLE' => $package['PACKAGE_NAME']];
|
|
|
+ } else {
|
|
|
+ $ids = $input['goodsId'] ?? [];
|
|
|
+ $quantities = $input['goodsNum'] ?? [];
|
|
|
+ if (!is_array($ids) || !is_array($quantities) || count($ids) !== count($quantities) || !$ids) {
|
|
|
+ throw new BadRequestHttpException('Select at least one valid product.');
|
|
|
+ }
|
|
|
+ foreach ($ids as $index => $id) {
|
|
|
+ $quantity = filter_var($quantities[$index], FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 99]]);
|
|
|
+ if ($quantity === false) {
|
|
|
+ throw new BadRequestHttpException('Product quantity is invalid.');
|
|
|
+ }
|
|
|
+ if ($quantity === 0) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ $product = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1', [':ID' => $id]);
|
|
|
+ $nature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID', [':GOODS_ID' => $id, ':COUNTRY_ID' => $input['countryId']]);
|
|
|
+ if (!$product || !$nature || (int) $product['STORE_NUMS'] < $quantity || !empty($product['INSTALMENT'])) {
|
|
|
+ throw new BadRequestHttpException(Yii::t('app', 'productsDoesSoldOut'));
|
|
|
+ }
|
|
|
+ $unitPrice = (float) $nature['MARKET_PRICE'];
|
|
|
+ $unitPv = (float) $product['PRICE_PV'];
|
|
|
+ $amount += $unitPrice * $quantity;
|
|
|
+ $pv += $unitPv * $quantity;
|
|
|
+ $goods[] = ['GOODS_ID' => $product['ID'], 'PRICE' => $unitPrice, 'PV' => $unitPv, 'BUY_NUMS' => $quantity, 'SKU_CODE' => $product['GOODS_NO'], 'GOODS_TITLE' => $product['GOODS_NAME']];
|
|
|
+ }
|
|
|
+ if (!$goods) {
|
|
|
+ throw new BadRequestHttpException('Select at least one valid product.');
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return [$amount, $pv, $goods];
|
|
|
+ }
|
|
|
+
|
|
|
+ public function completePaidDraft(string $orderSn, array $verifiedTransaction): array
|
|
|
+ {
|
|
|
+ $draft = GuestDeclarationDraft::findOne(['ORDER_SN' => $orderSn]);
|
|
|
+ if (!$draft) {
|
|
|
+ throw new NotFoundHttpException('Guest order draft was not found.');
|
|
|
+ }
|
|
|
+ if ($draft->STATUS === GuestDeclarationDraftStatus::COMPLETED) {
|
|
|
+ return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
|
|
|
+ }
|
|
|
+ if ($draft->STATUS === GuestDeclarationDraftStatus::MANUAL_REVIEW) {
|
|
|
+ return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
|
|
|
+ }
|
|
|
+ $fields = $verifiedTransaction['metadata']['custom_fields'] ?? [];
|
|
|
+ $metadataMatches = ($fields[0]['value'] ?? null) === $draft->ORDER_SN
|
|
|
+ && ($fields[1]['value'] ?? null) === 'guestUserDec';
|
|
|
+ if ($draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
|
|
|
+ && ($verifiedTransaction['status'] ?? null) === 'success'
|
|
|
+ && $metadataMatches
|
|
|
+ ) {
|
|
|
+ GuestDeclarationDraft::updateAll(
|
|
|
+ ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
|
|
|
+ ['ID' => $draft->ID]
|
|
|
+ );
|
|
|
+ return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
|
|
|
+ }
|
|
|
+ $expectedAmount = (int) round(((float) $draft->PAY_AMOUNT) * 100);
|
|
|
+ if ($draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
|
|
|
+ || ($verifiedTransaction['status'] ?? null) !== 'success'
|
|
|
+ || (string) ($verifiedTransaction['reference'] ?? '') !== (string) $draft->PAYMENT_REFERENCE
|
|
|
+ || (int) ($verifiedTransaction['amount'] ?? -1) !== $expectedAmount
|
|
|
+ || strtoupper((string) ($verifiedTransaction['currency'] ?? '')) !== strtoupper((string) $draft->CURRENCY)
|
|
|
+ ) {
|
|
|
+ if (($verifiedTransaction['reference'] ?? null) === $draft->PAYMENT_REFERENCE || $metadataMatches) {
|
|
|
+ GuestDeclarationDraft::updateAll(
|
|
|
+ ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
|
|
|
+ ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
|
|
|
+ );
|
|
|
+ return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
|
|
|
+ }
|
|
|
+ throw new BadRequestHttpException('Verified payment does not match this guest order.');
|
|
|
+ }
|
|
|
+ if (!$metadataMatches) {
|
|
|
+ GuestDeclarationDraft::updateAll(
|
|
|
+ ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
|
|
|
+ ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
|
|
|
+ );
|
|
|
+ return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
|
|
|
+ }
|
|
|
+ if ($draft->isExpired()) {
|
|
|
+ GuestDeclarationDraft::updateAll(
|
|
|
+ ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
|
|
|
+ ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
|
|
|
+ );
|
|
|
+ return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
|
|
|
+ }
|
|
|
+
|
|
|
+ $transaction = Yii::$app->db->beginTransaction();
|
|
|
+ $claimed = false;
|
|
|
+ try {
|
|
|
+ if (!GuestDeclarationDraft::claimForProcessing($orderSn)) {
|
|
|
+ $draft->refresh();
|
|
|
+ if ($draft->STATUS === GuestDeclarationDraftStatus::COMPLETED) {
|
|
|
+ $transaction->commit();
|
|
|
+ return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
|
|
|
+ }
|
|
|
+ throw new \RuntimeException('Guest order is already being processed.');
|
|
|
+ }
|
|
|
+ $claimed = true;
|
|
|
+ $draft->refresh();
|
|
|
+ $payload = $draft->getPayload();
|
|
|
+ $snapshot = $draft->getOrderSnapshot();
|
|
|
+ $loop = new ApproachDeclarationLoopForm();
|
|
|
+ $loop->scenario = 'userDec';
|
|
|
+ $loop->isGuestDeclaration = true;
|
|
|
+ $loop->guestOrderSn = $orderSn;
|
|
|
+ $loop->data = [$payload];
|
|
|
+ $approachOrder = $loop->add();
|
|
|
+ if (!$approachOrder instanceof ApproachOrder) {
|
|
|
+ throw new \RuntimeException('Unable to create the paid registration order.');
|
|
|
+ }
|
|
|
+ if (abs((float) $approachOrder->ORDER_AMOUNT - (float) $snapshot['amount']) > 0.000001
|
|
|
+ || abs((float) $approachOrder->PV - (float) $snapshot['pv']) > 0.000001
|
|
|
+ ) {
|
|
|
+ throw new \RuntimeException('Order price changed after payment; manual review is required.');
|
|
|
+ }
|
|
|
+ if (isset($approachOrder->USER_NAME) && $approachOrder->USER_NAME !== $payload['insertUserName']) {
|
|
|
+ throw new \RuntimeException('Created member does not match the guest order.');
|
|
|
+ }
|
|
|
+
|
|
|
+ $verify = new ApproachOrderForm();
|
|
|
+ $verify->scenario = 'verifyPayStack';
|
|
|
+ $verify->sn = $orderSn;
|
|
|
+ $verify->status = Yii::$app->params['orderStatus']['paid']['value'];
|
|
|
+ $verify->note = [
|
|
|
+ 'id' => $verifiedTransaction['id'] ?? null,
|
|
|
+ 'domain' => $verifiedTransaction['domain'] ?? null,
|
|
|
+ 'status' => $verifiedTransaction['status'],
|
|
|
+ 'reference' => $verifiedTransaction['reference'],
|
|
|
+ 'amount' => $verifiedTransaction['amount'],
|
|
|
+ 'created_at' => $verifiedTransaction['created_at'] ?? null,
|
|
|
+ 'paid_at' => $verifiedTransaction['paid_at'] ?? null,
|
|
|
+ 'channel' => $verifiedTransaction['channel'] ?? null,
|
|
|
+ 'currency' => $verifiedTransaction['currency'],
|
|
|
+ 'metadata' => $verifiedTransaction['metadata'],
|
|
|
+ 'email' => $verifiedTransaction['customer']['email'] ?? $verifiedTransaction['email'] ?? '',
|
|
|
+ ];
|
|
|
+ $verifiedOrder = $verify->verifyPayStack();
|
|
|
+ if (!$verifiedOrder) {
|
|
|
+ throw new \RuntimeException('Unable to finalize the paid registration order.');
|
|
|
+ }
|
|
|
+
|
|
|
+ $draft->USER_ID = $approachOrder->USER_ID;
|
|
|
+ $draft->PAYLOAD = json_encode(['insertUserName' => $payload['insertUserName']], JSON_UNESCAPED_UNICODE);
|
|
|
+ $draft->STATUS = GuestDeclarationDraftStatus::COMPLETED;
|
|
|
+ $draft->PAID_AT = time();
|
|
|
+ $draft->COMPLETED_AT = time();
|
|
|
+ $draft->UPDATED_AT = time();
|
|
|
+ if (!$draft->save(false)) {
|
|
|
+ throw new \RuntimeException('Unable to complete guest order draft.');
|
|
|
+ }
|
|
|
+ $transaction->commit();
|
|
|
+ return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
|
|
|
+ } catch (\Throwable $e) {
|
|
|
+ if ($transaction->isActive) {
|
|
|
+ $transaction->rollBack();
|
|
|
+ }
|
|
|
+ if ($claimed) {
|
|
|
+ GuestDeclarationDraft::updateAll(
|
|
|
+ ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
|
|
|
+ ['AND', ['ORDER_SN' => $orderSn], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
|
|
|
+ );
|
|
|
+ }
|
|
|
+ throw $e;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public function markPaymentFailed(string $reference, array $verifiedTransaction): void
|
|
|
+ {
|
|
|
+ $draft = GuestDeclarationDraft::findOne(['PAYMENT_REFERENCE' => $reference]);
|
|
|
+ if (!$draft || $draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
|
|
|
+ || ($verifiedTransaction['status'] ?? null) === 'success'
|
|
|
+ || (string) ($verifiedTransaction['reference'] ?? '') !== $reference
|
|
|
+ ) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ GuestDeclarationDraft::updateAll(
|
|
|
+ ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_FAILED, 'PAYMENT_REFERENCE' => null, 'PAYMENT_NOTE' => null, 'UPDATED_AT' => time()],
|
|
|
+ ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT], ['PAYMENT_REFERENCE' => $reference]]
|
|
|
+ );
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Require both unguessable draft id and its one-time bearer token.
|
|
|
+ */
|
|
|
+ private function loadAuthorizedDraft(string $draftId, string $accessToken): GuestDeclarationDraft
|
|
|
+ {
|
|
|
+ $draft = GuestDeclarationDraft::findOne(['ID' => $draftId]);
|
|
|
+ if (!$draft || !$draft->accessTokenMatches($accessToken)) {
|
|
|
+ throw new NotFoundHttpException('Guest order draft was not found.');
|
|
|
+ }
|
|
|
+ return $draft;
|
|
|
+ }
|
|
|
+}
|