GuestDeclarationOrderService.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. <?php
  2. namespace common\services;
  3. use common\helpers\GuestDeclarationDraftStatus;
  4. use common\helpers\Cache;
  5. use common\helpers\Form;
  6. use common\helpers\user\Info;
  7. use common\models\Countries;
  8. use common\models\Currency;
  9. use common\models\GuestDeclarationDraft;
  10. use common\models\ApproachOrder;
  11. use common\models\DeclarationPackage;
  12. use common\models\ShopGoods;
  13. use common\models\ShopGoodsNature;
  14. use common\models\Region;
  15. use common\models\forms\ApproachDeclarationForm;
  16. use common\models\forms\ApproachDeclarationLoopForm;
  17. use common\models\forms\ApproachOrderForm;
  18. use common\models\User;
  19. use common\models\UserNetwork;
  20. use common\models\UserRelation;
  21. use Yii;
  22. use yii\web\BadRequestHttpException;
  23. use yii\web\NotFoundHttpException;
  24. /** Handles the public, pre-payment part of a guest registration order. */
  25. class GuestDeclarationOrderService
  26. {
  27. private const DRAFT_TTL = 86400;
  28. public function createDraft(string $countryId): array
  29. {
  30. $country = Countries::getById($countryId);
  31. if (!$country || empty($country['ACTIVE'])) {
  32. throw new BadRequestHttpException('Unsupported country.');
  33. }
  34. $currency = Currency::getById((string) $country['LOCAL_CURRENCY_ID']);
  35. if (!$currency || empty($currency['ACTIVE']) || empty($currency['CODE'])) {
  36. throw new BadRequestHttpException('Payment currency is unavailable.');
  37. }
  38. $token = Yii::$app->security->generateRandomString(64);
  39. $username = Info::generateWebName($countryId);
  40. if (!$username) {
  41. throw new \RuntimeException('Unable to generate a member number.');
  42. }
  43. $draft = new GuestDeclarationDraft();
  44. $draft->ID = Yii::$app->security->generateRandomString(32);
  45. $draft->ORDER_SN = 'OS' . strtoupper(bin2hex(random_bytes(12)));
  46. $draft->ACCESS_TOKEN_HASH = hash('sha256', $token);
  47. $draft->STATUS = GuestDeclarationDraftStatus::DRAFT;
  48. $draft->PAYLOAD = '{}';
  49. $draft->ORDER_SNAPSHOT = '{}';
  50. $draft->PAY_AMOUNT = 0;
  51. $draft->CURRENCY = strtoupper($currency['CODE']);
  52. $draft->CREATED_AT = time();
  53. $draft->EXPIRES_AT = time() + self::DRAFT_TTL;
  54. // This is a proposal only. The number is checked again before payment completion.
  55. $draft->USER_ID = null;
  56. $draft->PAYLOAD = json_encode([
  57. 'countryId' => $countryId,
  58. 'insertUserName' => $username,
  59. ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  60. if (!$draft->save()) {
  61. throw new \RuntimeException('Unable to create guest order draft.');
  62. }
  63. if (!Yii::$app->redis->setnx('key_' . $username, $username)) {
  64. $draft->delete();
  65. throw new \RuntimeException('Unable to reserve a unique member number. Please retry.');
  66. }
  67. Yii::$app->redis->expire('key_' . $username, self::DRAFT_TTL + 600);
  68. return [
  69. 'draftId' => $draft->ID,
  70. 'accessToken' => $token,
  71. 'insertUserName' => $username,
  72. 'expiresAt' => (int) $draft->EXPIRES_AT,
  73. 'currency' => $draft->CURRENCY,
  74. ];
  75. }
  76. public function getDraftStatus(string $draftId, string $accessToken): array
  77. {
  78. $draft = $this->loadAuthorizedDraft($draftId, $accessToken);
  79. if ($draft->STATUS === GuestDeclarationDraftStatus::PAYMENT_INITIALIZING && (int) $draft->UPDATED_AT < time() - 900) {
  80. $draft->transitionTo(GuestDeclarationDraftStatus::MANUAL_REVIEW);
  81. } elseif ($draft->isExpired() && in_array($draft->STATUS, [GuestDeclarationDraftStatus::DRAFT, GuestDeclarationDraftStatus::PENDING_PAYMENT], true)) {
  82. $draft->transitionTo(GuestDeclarationDraftStatus::EXPIRED);
  83. }
  84. return [
  85. 'status' => $draft->STATUS,
  86. 'orderSn' => $draft->STATUS === GuestDeclarationDraftStatus::COMPLETED ? $draft->ORDER_SN : null,
  87. 'userName' => $draft->STATUS === GuestDeclarationDraftStatus::COMPLETED ? ($draft->getPayload()['insertUserName'] ?? null) : null,
  88. ];
  89. }
  90. public function submitDraft(string $draftId, string $accessToken, array $input): array
  91. {
  92. $draft = $this->loadAuthorizedDraft($draftId, $accessToken);
  93. if ($draft->isExpired()) {
  94. $draft->transitionTo(GuestDeclarationDraftStatus::EXPIRED);
  95. throw new BadRequestHttpException('Guest order draft has expired.');
  96. }
  97. if ($draft->STATUS === GuestDeclarationDraftStatus::PENDING_PAYMENT) {
  98. return $this->paymentResponse($draft);
  99. }
  100. if ($draft->STATUS === GuestDeclarationDraftStatus::PAYMENT_INITIALIZING) {
  101. throw new BadRequestHttpException('Payment initialization is in progress.');
  102. }
  103. if (!in_array($draft->STATUS, [GuestDeclarationDraftStatus::DRAFT, GuestDeclarationDraftStatus::PAYMENT_FAILED], true)) {
  104. throw new BadRequestHttpException('Guest order draft cannot be submitted in its current state.');
  105. }
  106. foreach (['amount', 'payAmount', 'currency', 'pv', 'exchangeRate', 'goodsTitle', 'price', 'realPrice'] as $untrustedField) {
  107. if (array_key_exists($untrustedField, $input)) {
  108. throw new BadRequestHttpException('Price and product fields are calculated by the server.');
  109. }
  110. }
  111. $payload = $draft->getPayload();
  112. $countryId = (string) ($payload['countryId'] ?? '');
  113. unset($input['draftId'], $input['accessToken'], $input['allData'], $input['isGuestDeclaration'], $input['guestOrderSn'], $input['_insertUserId']);
  114. $input['insertUserName'] = $payload['insertUserName'] ?? '';
  115. $input['countryId'] = $countryId;
  116. $input['goodsId'] = $input['goodsId'] ?? [];
  117. $input['goodsNum'] = $input['goodsNum'] ?? [];
  118. $input['type'] = ApproachDeclarationForm::TYPE_ZC;
  119. $input['payType'] = 'pay_stack';
  120. $input['province'] = !empty($input['province']) ? $input['province'] : 1;
  121. $input['city'] = !empty($input['city']) ? $input['city'] : 1;
  122. $input['county'] = !empty($input['county']) ? $input['county'] : 1;
  123. $referrerName = trim((string) ($input['conUserName'] ?? ''));
  124. $sponsorName = trim((string) ($input['recUserName'] ?? ''));
  125. $referrerId = Info::getUserIdByUserName($referrerName);
  126. $sponsorId = Info::getUserIdByUserName($sponsorName);
  127. $relation = $referrerId ? UserRelation::findOneAsArray('USER_ID=:USER_ID', [':USER_ID' => $referrerId]) : null;
  128. $parentIds = $relation ? array_map('strval', explode(',', (string) $relation['PARENT_UIDS'])) : [];
  129. if (!$referrerId || !$sponsorId || ((string) $sponsorId !== (string) $referrerId && !in_array((string) $sponsorId, $parentIds, true))) {
  130. throw new BadRequestHttpException(Yii::t('app', 'fillSponsorUpline'));
  131. }
  132. $stockistName = trim((string) ($input['decUserName'] ?? ''));
  133. if ($stockistName === '' || !User::find()->where(['USER_NAME' => $stockistName, 'IS_DEC' => 1])->exists()) {
  134. throw new BadRequestHttpException(Yii::t('app', 'stockistDoesNotExist'));
  135. }
  136. if ((string) $input['province'] !== '1' && !Region::getWarehouseByCode($input['province'])) {
  137. throw new BadRequestHttpException(Yii::t('app', 'deliveryTemporarilyNotSupported'));
  138. }
  139. $bottomPlace = UserNetwork::getBottomPlace($referrerId, '', 'left');
  140. $bottom = UserNetwork::find()->select('USER_ID')->where(['LOCATION_TAG' => $bottomPlace])->asArray()->one();
  141. $bottomUser = $bottom ? User::findOneAsArray(['ID' => $bottom['USER_ID']], [], 'USER_NAME') : null;
  142. if (!$bottomUser) {
  143. throw new BadRequestHttpException(Yii::t('app', 'stockistDoesNotExist'));
  144. }
  145. $input['conUserName'] = $bottomUser['USER_NAME'];
  146. $input['recUserName'] = $referrerName;
  147. $input['bottomUserName'] = $sponsorName;
  148. $input['location'] = 1;
  149. $form = new ApproachDeclarationForm();
  150. $form->scenario = 'userDec';
  151. $explicitlyAllowedAttributes = [
  152. 'bottomUserName', 'payType', 'countryId', 'packageId', 'goodsId', 'goodsNum',
  153. 'email', 'languageId',
  154. ];
  155. $allowedNames = array_unique(array_merge($form->safeAttributes(), $explicitlyAllowedAttributes));
  156. $allowedInput = array_flip($allowedNames);
  157. unset($allowedInput['allData']);
  158. $input = array_intersect_key($input, $allowedInput);
  159. foreach ($input as $name => $value) {
  160. if (in_array($name, $allowedNames, true)) {
  161. $form->$name = $value;
  162. }
  163. }
  164. $form->bottomUserName = $sponsorName;
  165. $form->allData = [$input];
  166. if (!$form->validate()) {
  167. throw new BadRequestHttpException(Form::formatErrorsForApi($form->getErrors()));
  168. }
  169. if (User::find()->where(['USER_NAME' => $input['insertUserName']])->exists()
  170. || Yii::$app->redis->get('key_' . $input['insertUserName']) !== $input['insertUserName']
  171. ) {
  172. throw new BadRequestHttpException(Yii::t('app', 'memberNumberExpired'));
  173. }
  174. [$amount, $pv, $goods] = $this->quote($input);
  175. $levels = Cache::getDecLevelConfig();
  176. $minimumPv = $levels ? min(array_map(static function ($level) { return (float) $level['PERF']; }, $levels)) : 0;
  177. if ($pv < $minimumPv) {
  178. throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanSelectedBV'));
  179. }
  180. if ((string) ($input['decWay'] ?? '') !== '1') {
  181. $selectedLevel = $levels[$input['decLv'] ?? ''] ?? null;
  182. if (!$selectedLevel) {
  183. throw new BadRequestHttpException(Yii::t('app', 'pleaseSelectTheEntryLevel'));
  184. }
  185. if ($pv < (float) $selectedLevel['PERF']) {
  186. throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanSelectedBV'));
  187. }
  188. $actualLevel = null;
  189. foreach ($levels as $levelId => $level) {
  190. if ($pv >= (float) $level['PERF']) {
  191. $actualLevel = $levelId;
  192. }
  193. }
  194. if ($actualLevel !== null && (string) $input['decLv'] !== (string) $actualLevel) {
  195. throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanNextSelectedLevelBV'));
  196. }
  197. }
  198. if ($amount <= 0 || empty($input['email']) || !filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
  199. throw new BadRequestHttpException('A valid payment email and positive order amount are required.');
  200. }
  201. $country = Countries::getById($countryId);
  202. $currency = Currency::getById((string) $country['LOCAL_CURRENCY_ID']);
  203. $orderSn = $draft->ORDER_SN;
  204. $input['password'] = Yii::$app->security->generatePasswordHash((string) $input['password']);
  205. $input['payPassword'] = Yii::$app->security->generatePasswordHash((string) $input['payPassword']);
  206. $storedPayload = json_encode($input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  207. $reserved = GuestDeclarationDraft::updateAll(
  208. ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_INITIALIZING, 'UPDATED_AT' => time()],
  209. ['AND', ['ID' => $draft->ID], ['STATUS' => $draft->STATUS], ['>' , 'EXPIRES_AT', time()]]
  210. );
  211. if ($reserved !== 1) {
  212. $draft->refresh();
  213. if ($draft->STATUS === GuestDeclarationDraftStatus::PENDING_PAYMENT) {
  214. return $this->paymentResponse($draft);
  215. }
  216. throw new BadRequestHttpException('Guest order draft is already being submitted.');
  217. }
  218. $paymentReference = 'GD' . strtoupper(bin2hex(random_bytes(12)));
  219. $init = \common\helpers\PayStack::transactionInit(
  220. strtoupper($currency['CODE']),
  221. $amount,
  222. $input['email'],
  223. ['custom_fields' => [
  224. ['display_name' => 'Order SN', 'variable_name' => 'orderSn', 'value' => $orderSn],
  225. ['display_name' => 'Order Type', 'variable_name' => 'orderType', 'value' => 'guestUserDec'],
  226. ]],
  227. $paymentReference
  228. );
  229. if (empty($init['status']) || empty($init['data']['reference']) || empty($init['data']['authorization_url'])) {
  230. GuestDeclarationDraft::updateAll(
  231. ['STATUS' => GuestDeclarationDraftStatus::DRAFT, 'UPDATED_AT' => time()],
  232. ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_INITIALIZING]]
  233. );
  234. throw new \RuntimeException('Unable to initialize payment. Please retry.');
  235. }
  236. $draft->PAYLOAD = $storedPayload;
  237. $draft->ORDER_SNAPSHOT = json_encode(['amount' => $amount, 'pv' => $pv, 'goods' => $goods], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  238. $draft->PAY_AMOUNT = $amount;
  239. $draft->CURRENCY = strtoupper($currency['CODE']);
  240. $draft->PAYMENT_REFERENCE = $init['data']['reference'];
  241. $draft->PAYMENT_NOTE = json_encode([
  242. 'authorization_url' => $init['data']['authorization_url'],
  243. 'access_code' => $init['data']['access_code'] ?? null,
  244. ]);
  245. $draft->STATUS = GuestDeclarationDraftStatus::PENDING_PAYMENT;
  246. $draft->UPDATED_AT = time();
  247. if (!$draft->save(false)) {
  248. GuestDeclarationDraft::updateAll([
  249. 'STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW,
  250. 'PAYLOAD' => $draft->PAYLOAD,
  251. 'ORDER_SNAPSHOT' => $draft->ORDER_SNAPSHOT,
  252. 'PAY_AMOUNT' => $draft->PAY_AMOUNT,
  253. 'CURRENCY' => $draft->CURRENCY,
  254. 'PAYMENT_REFERENCE' => $draft->PAYMENT_REFERENCE,
  255. 'PAYMENT_NOTE' => $draft->PAYMENT_NOTE,
  256. 'UPDATED_AT' => time(),
  257. ], ['ID' => $draft->ID]);
  258. throw new \RuntimeException('Payment started but its draft could not be saved; manual review is required.');
  259. }
  260. return $this->paymentResponse($draft);
  261. }
  262. private function paymentResponse(GuestDeclarationDraft $draft): array
  263. {
  264. $payment = json_decode((string) $draft->PAYMENT_NOTE, true) ?: [];
  265. return [
  266. 'orderSn' => $draft->ORDER_SN,
  267. 'amount' => (float) $draft->PAY_AMOUNT,
  268. 'currency' => $draft->CURRENCY,
  269. 'reference' => $draft->PAYMENT_REFERENCE,
  270. 'authorizationUrl' => $payment['authorization_url'] ?? null,
  271. 'accessCode' => $payment['access_code'] ?? null,
  272. ];
  273. }
  274. private function quote(array $input): array
  275. {
  276. $goods = [];
  277. $amount = 0.0;
  278. $pv = 0.0;
  279. if (!empty($input['decWay']) && (string) $input['decWay'] === '1') {
  280. $package = DeclarationPackage::findOneAsArray('ID=:ID AND STATUS=1', [':ID' => $input['packageId'] ?? null]);
  281. if (!$package || (int) $package['STORE_NUMS'] <= 0) {
  282. throw new BadRequestHttpException(Yii::t('app', 'productsDoesSoldOut'));
  283. }
  284. if ((string) ($input['decLv'] ?? '') !== (string) $package['LEVEL_ID']) {
  285. throw new BadRequestHttpException(Yii::t('app', 'pleaseSelectTheEntryLevel'));
  286. }
  287. $amount = (float) $package['AMOUNT'];
  288. $pv = (float) $package['PV'];
  289. $goods[] = ['GOODS_ID' => $package['ID'], 'PRICE' => $amount, 'PV' => $pv, 'BUY_NUMS' => 1, 'SKU_CODE' => $package['PACKAGE_NO'], 'GOODS_TITLE' => $package['PACKAGE_NAME']];
  290. } else {
  291. $ids = $input['goodsId'] ?? [];
  292. $quantities = $input['goodsNum'] ?? [];
  293. if (!is_array($ids) || !is_array($quantities) || count($ids) !== count($quantities) || !$ids) {
  294. throw new BadRequestHttpException('Select at least one valid product.');
  295. }
  296. foreach ($ids as $index => $id) {
  297. $quantity = filter_var($quantities[$index], FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 99]]);
  298. if ($quantity === false) {
  299. throw new BadRequestHttpException('Product quantity is invalid.');
  300. }
  301. if ($quantity === 0) {
  302. continue;
  303. }
  304. $product = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1', [':ID' => $id]);
  305. $nature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID', [':GOODS_ID' => $id, ':COUNTRY_ID' => $input['countryId']]);
  306. if (!$product || !$nature || (int) $product['STORE_NUMS'] < $quantity || !empty($product['INSTALMENT'])) {
  307. throw new BadRequestHttpException(Yii::t('app', 'productsDoesSoldOut'));
  308. }
  309. $unitPrice = (float) $nature['MARKET_PRICE'];
  310. $unitPv = (float) $product['PRICE_PV'];
  311. $amount += $unitPrice * $quantity;
  312. $pv += $unitPv * $quantity;
  313. $goods[] = ['GOODS_ID' => $product['ID'], 'PRICE' => $unitPrice, 'PV' => $unitPv, 'BUY_NUMS' => $quantity, 'SKU_CODE' => $product['GOODS_NO'], 'GOODS_TITLE' => $product['GOODS_NAME']];
  314. }
  315. if (!$goods) {
  316. throw new BadRequestHttpException('Select at least one valid product.2');
  317. }
  318. }
  319. return [$amount, $pv, $goods];
  320. }
  321. public function completePaidDraft(string $orderSn, array $verifiedTransaction): array
  322. {
  323. $draft = GuestDeclarationDraft::findOne(['ORDER_SN' => $orderSn]);
  324. if (!$draft) {
  325. throw new NotFoundHttpException('Guest order draft was not found.');
  326. }
  327. if ($draft->STATUS === GuestDeclarationDraftStatus::COMPLETED) {
  328. return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
  329. }
  330. if ($draft->STATUS === GuestDeclarationDraftStatus::MANUAL_REVIEW) {
  331. return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
  332. }
  333. $fields = $verifiedTransaction['metadata']['custom_fields'] ?? [];
  334. $metadataMatches = ($fields[0]['value'] ?? null) === $draft->ORDER_SN
  335. && ($fields[1]['value'] ?? null) === 'guestUserDec';
  336. if ($draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
  337. && ($verifiedTransaction['status'] ?? null) === 'success'
  338. && $metadataMatches
  339. ) {
  340. GuestDeclarationDraft::updateAll(
  341. ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
  342. ['ID' => $draft->ID]
  343. );
  344. return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
  345. }
  346. $expectedAmount = (int) round(((float) $draft->PAY_AMOUNT) * 100);
  347. if ($draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
  348. || ($verifiedTransaction['status'] ?? null) !== 'success'
  349. || (string) ($verifiedTransaction['reference'] ?? '') !== (string) $draft->PAYMENT_REFERENCE
  350. || (int) ($verifiedTransaction['amount'] ?? -1) !== $expectedAmount
  351. || strtoupper((string) ($verifiedTransaction['currency'] ?? '')) !== strtoupper((string) $draft->CURRENCY)
  352. ) {
  353. if (($verifiedTransaction['reference'] ?? null) === $draft->PAYMENT_REFERENCE || $metadataMatches) {
  354. GuestDeclarationDraft::updateAll(
  355. ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
  356. ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
  357. );
  358. return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
  359. }
  360. throw new BadRequestHttpException('Verified payment does not match this guest order.');
  361. }
  362. if (!$metadataMatches) {
  363. GuestDeclarationDraft::updateAll(
  364. ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
  365. ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
  366. );
  367. return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
  368. }
  369. if ($draft->isExpired()) {
  370. GuestDeclarationDraft::updateAll(
  371. ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
  372. ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
  373. );
  374. return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
  375. }
  376. $transaction = Yii::$app->db->beginTransaction();
  377. $claimed = false;
  378. try {
  379. if (!GuestDeclarationDraft::claimForProcessing($orderSn)) {
  380. $draft->refresh();
  381. if ($draft->STATUS === GuestDeclarationDraftStatus::COMPLETED) {
  382. $transaction->commit();
  383. return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
  384. }
  385. throw new \RuntimeException('Guest order is already being processed.');
  386. }
  387. $claimed = true;
  388. $draft->refresh();
  389. $payload = $draft->getPayload();
  390. $snapshot = $draft->getOrderSnapshot();
  391. $loop = new ApproachDeclarationLoopForm();
  392. $loop->scenario = 'userDec';
  393. $loop->isGuestDeclaration = true;
  394. $loop->guestOrderSn = $orderSn;
  395. $loop->data = [$payload];
  396. $approachOrder = $loop->add();
  397. if (!$approachOrder instanceof ApproachOrder) {
  398. throw new \RuntimeException('Unable to create the paid registration order.');
  399. }
  400. if (abs((float) $approachOrder->ORDER_AMOUNT - (float) $snapshot['amount']) > 0.000001
  401. || abs((float) $approachOrder->PV - (float) $snapshot['pv']) > 0.000001
  402. ) {
  403. throw new \RuntimeException('Order price changed after payment; manual review is required.');
  404. }
  405. if (isset($approachOrder->USER_NAME) && $approachOrder->USER_NAME !== $payload['insertUserName']) {
  406. throw new \RuntimeException('Created member does not match the guest order.');
  407. }
  408. $verify = new ApproachOrderForm();
  409. $verify->scenario = 'verifyPayStack';
  410. $verify->sn = $orderSn;
  411. $verify->status = Yii::$app->params['orderStatus']['paid']['value'];
  412. $verify->note = [
  413. 'id' => $verifiedTransaction['id'] ?? null,
  414. 'domain' => $verifiedTransaction['domain'] ?? null,
  415. 'status' => $verifiedTransaction['status'],
  416. 'reference' => $verifiedTransaction['reference'],
  417. 'amount' => $verifiedTransaction['amount'],
  418. 'created_at' => $verifiedTransaction['created_at'] ?? null,
  419. 'paid_at' => $verifiedTransaction['paid_at'] ?? null,
  420. 'channel' => $verifiedTransaction['channel'] ?? null,
  421. 'currency' => $verifiedTransaction['currency'],
  422. 'metadata' => $verifiedTransaction['metadata'],
  423. 'email' => $verifiedTransaction['customer']['email'] ?? $verifiedTransaction['email'] ?? '',
  424. ];
  425. $verifiedOrder = $verify->verifyPayStack();
  426. if (!$verifiedOrder) {
  427. throw new \RuntimeException('Unable to finalize the paid registration order.');
  428. }
  429. $draft->USER_ID = $approachOrder->USER_ID;
  430. $draft->PAYLOAD = json_encode(['insertUserName' => $payload['insertUserName']], JSON_UNESCAPED_UNICODE);
  431. $draft->STATUS = GuestDeclarationDraftStatus::COMPLETED;
  432. $draft->PAID_AT = time();
  433. $draft->COMPLETED_AT = time();
  434. $draft->UPDATED_AT = time();
  435. if (!$draft->save(false)) {
  436. throw new \RuntimeException('Unable to complete guest order draft.');
  437. }
  438. $transaction->commit();
  439. return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
  440. } catch (\Throwable $e) {
  441. if ($transaction->isActive) {
  442. $transaction->rollBack();
  443. }
  444. if ($claimed) {
  445. GuestDeclarationDraft::updateAll(
  446. ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
  447. ['AND', ['ORDER_SN' => $orderSn], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
  448. );
  449. }
  450. throw $e;
  451. }
  452. }
  453. public function markPaymentFailed(string $reference, array $verifiedTransaction): void
  454. {
  455. $draft = GuestDeclarationDraft::findOne(['PAYMENT_REFERENCE' => $reference]);
  456. if (!$draft || $draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
  457. || ($verifiedTransaction['status'] ?? null) === 'success'
  458. || (string) ($verifiedTransaction['reference'] ?? '') !== $reference
  459. ) {
  460. return;
  461. }
  462. GuestDeclarationDraft::updateAll(
  463. ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_FAILED, 'PAYMENT_REFERENCE' => null, 'PAYMENT_NOTE' => null, 'UPDATED_AT' => time()],
  464. ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT], ['PAYMENT_REFERENCE' => $reference]]
  465. );
  466. }
  467. /**
  468. * Require both unguessable draft id and its one-time bearer token.
  469. */
  470. private function loadAuthorizedDraft(string $draftId, string $accessToken): GuestDeclarationDraft
  471. {
  472. $draft = GuestDeclarationDraft::findOne(['ID' => $draftId]);
  473. if (!$draft || !$draft->accessTokenMatches($accessToken)) {
  474. throw new NotFoundHttpException('Guest order draft was not found.');
  475. }
  476. return $draft;
  477. }
  478. }