GuestDeclarationOrderService.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. foreach ($input as $name => $value) {
  152. if (in_array($name, $form->safeAttributes(), true) && $name !== 'allData') {
  153. $form->$name = $value;
  154. }
  155. }
  156. $form->bottomUserName = $sponsorName;
  157. $allowedInput = array_flip(array_merge($form->safeAttributes(), ['bottomUserName', 'payType', 'countryId']));
  158. unset($allowedInput['allData']);
  159. $input = array_intersect_key($input, $allowedInput);
  160. $form->allData = [$input];
  161. if (!$form->validate()) {
  162. throw new BadRequestHttpException(Form::formatErrorsForApi($form->getErrors()));
  163. }
  164. if (User::find()->where(['USER_NAME' => $input['insertUserName']])->exists()
  165. || Yii::$app->redis->get('key_' . $input['insertUserName']) !== $input['insertUserName']
  166. ) {
  167. throw new BadRequestHttpException(Yii::t('app', 'memberNumberExpired'));
  168. }
  169. [$amount, $pv, $goods] = $this->quote($input);
  170. $levels = Cache::getDecLevelConfig();
  171. $minimumPv = $levels ? min(array_map(static function ($level) { return (float) $level['PERF']; }, $levels)) : 0;
  172. if ($pv < $minimumPv) {
  173. throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanSelectedBV'));
  174. }
  175. if ((string) ($input['decWay'] ?? '') !== '1') {
  176. $selectedLevel = $levels[$input['decLv'] ?? ''] ?? null;
  177. if (!$selectedLevel) {
  178. throw new BadRequestHttpException(Yii::t('app', 'pleaseSelectTheEntryLevel'));
  179. }
  180. if ($pv < (float) $selectedLevel['PERF']) {
  181. throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanSelectedBV'));
  182. }
  183. $actualLevel = null;
  184. foreach ($levels as $levelId => $level) {
  185. if ($pv >= (float) $level['PERF']) {
  186. $actualLevel = $levelId;
  187. }
  188. }
  189. if ($actualLevel !== null && (string) $input['decLv'] !== (string) $actualLevel) {
  190. throw new BadRequestHttpException(Yii::t('app', 'totalBVCanNotLessThanNextSelectedLevelBV'));
  191. }
  192. }
  193. if ($amount <= 0 || empty($input['email']) || !filter_var($input['email'], FILTER_VALIDATE_EMAIL)) {
  194. throw new BadRequestHttpException('A valid payment email and positive order amount are required.');
  195. }
  196. $country = Countries::getById($countryId);
  197. $currency = Currency::getById((string) $country['LOCAL_CURRENCY_ID']);
  198. $orderSn = $draft->ORDER_SN;
  199. $input['password'] = Yii::$app->security->generatePasswordHash((string) $input['password']);
  200. $input['payPassword'] = Yii::$app->security->generatePasswordHash((string) $input['payPassword']);
  201. $storedPayload = json_encode($input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  202. $reserved = GuestDeclarationDraft::updateAll(
  203. ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_INITIALIZING, 'UPDATED_AT' => time()],
  204. ['AND', ['ID' => $draft->ID], ['STATUS' => $draft->STATUS], ['>' , 'EXPIRES_AT', time()]]
  205. );
  206. if ($reserved !== 1) {
  207. $draft->refresh();
  208. if ($draft->STATUS === GuestDeclarationDraftStatus::PENDING_PAYMENT) {
  209. return $this->paymentResponse($draft);
  210. }
  211. throw new BadRequestHttpException('Guest order draft is already being submitted.');
  212. }
  213. $paymentReference = 'GD' . strtoupper(bin2hex(random_bytes(12)));
  214. $init = \common\helpers\PayStack::transactionInit(
  215. strtoupper($currency['CODE']),
  216. $amount,
  217. $input['email'],
  218. ['custom_fields' => [
  219. ['display_name' => 'Order SN', 'variable_name' => 'orderSn', 'value' => $orderSn],
  220. ['display_name' => 'Order Type', 'variable_name' => 'orderType', 'value' => 'guestUserDec'],
  221. ]],
  222. $paymentReference
  223. );
  224. if (empty($init['status']) || empty($init['data']['reference']) || empty($init['data']['authorization_url'])) {
  225. GuestDeclarationDraft::updateAll(
  226. ['STATUS' => GuestDeclarationDraftStatus::DRAFT, 'UPDATED_AT' => time()],
  227. ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_INITIALIZING]]
  228. );
  229. throw new \RuntimeException('Unable to initialize payment. Please retry.');
  230. }
  231. $draft->PAYLOAD = $storedPayload;
  232. $draft->ORDER_SNAPSHOT = json_encode(['amount' => $amount, 'pv' => $pv, 'goods' => $goods], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  233. $draft->PAY_AMOUNT = $amount;
  234. $draft->CURRENCY = strtoupper($currency['CODE']);
  235. $draft->PAYMENT_REFERENCE = $init['data']['reference'];
  236. $draft->PAYMENT_NOTE = json_encode([
  237. 'authorization_url' => $init['data']['authorization_url'],
  238. 'access_code' => $init['data']['access_code'] ?? null,
  239. ]);
  240. $draft->STATUS = GuestDeclarationDraftStatus::PENDING_PAYMENT;
  241. $draft->UPDATED_AT = time();
  242. if (!$draft->save(false)) {
  243. GuestDeclarationDraft::updateAll([
  244. 'STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW,
  245. 'PAYLOAD' => $draft->PAYLOAD,
  246. 'ORDER_SNAPSHOT' => $draft->ORDER_SNAPSHOT,
  247. 'PAY_AMOUNT' => $draft->PAY_AMOUNT,
  248. 'CURRENCY' => $draft->CURRENCY,
  249. 'PAYMENT_REFERENCE' => $draft->PAYMENT_REFERENCE,
  250. 'PAYMENT_NOTE' => $draft->PAYMENT_NOTE,
  251. 'UPDATED_AT' => time(),
  252. ], ['ID' => $draft->ID]);
  253. throw new \RuntimeException('Payment started but its draft could not be saved; manual review is required.');
  254. }
  255. return $this->paymentResponse($draft);
  256. }
  257. private function paymentResponse(GuestDeclarationDraft $draft): array
  258. {
  259. $payment = json_decode((string) $draft->PAYMENT_NOTE, true) ?: [];
  260. return [
  261. 'orderSn' => $draft->ORDER_SN,
  262. 'amount' => (float) $draft->PAY_AMOUNT,
  263. 'currency' => $draft->CURRENCY,
  264. 'reference' => $draft->PAYMENT_REFERENCE,
  265. 'authorizationUrl' => $payment['authorization_url'] ?? null,
  266. 'accessCode' => $payment['access_code'] ?? null,
  267. ];
  268. }
  269. private function quote(array $input): array
  270. {
  271. $goods = [];
  272. $amount = 0.0;
  273. $pv = 0.0;
  274. if (!empty($input['decWay']) && (string) $input['decWay'] === '1') {
  275. $package = DeclarationPackage::findOneAsArray('ID=:ID AND STATUS=1', [':ID' => $input['packageId'] ?? null]);
  276. if (!$package || (int) $package['STORE_NUMS'] <= 0) {
  277. throw new BadRequestHttpException(Yii::t('app', 'productsDoesSoldOut'));
  278. }
  279. if ((string) ($input['decLv'] ?? '') !== (string) $package['LEVEL_ID']) {
  280. throw new BadRequestHttpException(Yii::t('app', 'pleaseSelectTheEntryLevel'));
  281. }
  282. $amount = (float) $package['AMOUNT'];
  283. $pv = (float) $package['PV'];
  284. $goods[] = ['GOODS_ID' => $package['ID'], 'PRICE' => $amount, 'PV' => $pv, 'BUY_NUMS' => 1, 'SKU_CODE' => $package['PACKAGE_NO'], 'GOODS_TITLE' => $package['PACKAGE_NAME']];
  285. } else {
  286. $ids = $input['goodsId'] ?? [];
  287. $quantities = $input['goodsNum'] ?? [];
  288. if (!is_array($ids) || !is_array($quantities) || count($ids) !== count($quantities) || !$ids) {
  289. throw new BadRequestHttpException('Select at least one valid product.');
  290. }
  291. foreach ($ids as $index => $id) {
  292. $quantity = filter_var($quantities[$index], FILTER_VALIDATE_INT, ['options' => ['min_range' => 0, 'max_range' => 99]]);
  293. if ($quantity === false) {
  294. throw new BadRequestHttpException('Product quantity is invalid.');
  295. }
  296. if ($quantity === 0) {
  297. continue;
  298. }
  299. $product = ShopGoods::findOneAsArray('ID=:ID AND STATUS=1', [':ID' => $id]);
  300. $nature = ShopGoodsNature::findOneAsArray('GOODS_ID=:GOODS_ID AND COUNTRY_ID=:COUNTRY_ID', [':GOODS_ID' => $id, ':COUNTRY_ID' => $input['countryId']]);
  301. if (!$product || !$nature || (int) $product['STORE_NUMS'] < $quantity || !empty($product['INSTALMENT'])) {
  302. throw new BadRequestHttpException(Yii::t('app', 'productsDoesSoldOut'));
  303. }
  304. $unitPrice = (float) $nature['MARKET_PRICE'];
  305. $unitPv = (float) $product['PRICE_PV'];
  306. $amount += $unitPrice * $quantity;
  307. $pv += $unitPv * $quantity;
  308. $goods[] = ['GOODS_ID' => $product['ID'], 'PRICE' => $unitPrice, 'PV' => $unitPv, 'BUY_NUMS' => $quantity, 'SKU_CODE' => $product['GOODS_NO'], 'GOODS_TITLE' => $product['GOODS_NAME']];
  309. }
  310. if (!$goods) {
  311. throw new BadRequestHttpException('Select at least one valid product.');
  312. }
  313. }
  314. return [$amount, $pv, $goods];
  315. }
  316. public function completePaidDraft(string $orderSn, array $verifiedTransaction): array
  317. {
  318. $draft = GuestDeclarationDraft::findOne(['ORDER_SN' => $orderSn]);
  319. if (!$draft) {
  320. throw new NotFoundHttpException('Guest order draft was not found.');
  321. }
  322. if ($draft->STATUS === GuestDeclarationDraftStatus::COMPLETED) {
  323. return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
  324. }
  325. if ($draft->STATUS === GuestDeclarationDraftStatus::MANUAL_REVIEW) {
  326. return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
  327. }
  328. $fields = $verifiedTransaction['metadata']['custom_fields'] ?? [];
  329. $metadataMatches = ($fields[0]['value'] ?? null) === $draft->ORDER_SN
  330. && ($fields[1]['value'] ?? null) === 'guestUserDec';
  331. if ($draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
  332. && ($verifiedTransaction['status'] ?? null) === 'success'
  333. && $metadataMatches
  334. ) {
  335. GuestDeclarationDraft::updateAll(
  336. ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
  337. ['ID' => $draft->ID]
  338. );
  339. return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
  340. }
  341. $expectedAmount = (int) round(((float) $draft->PAY_AMOUNT) * 100);
  342. if ($draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
  343. || ($verifiedTransaction['status'] ?? null) !== 'success'
  344. || (string) ($verifiedTransaction['reference'] ?? '') !== (string) $draft->PAYMENT_REFERENCE
  345. || (int) ($verifiedTransaction['amount'] ?? -1) !== $expectedAmount
  346. || strtoupper((string) ($verifiedTransaction['currency'] ?? '')) !== strtoupper((string) $draft->CURRENCY)
  347. ) {
  348. if (($verifiedTransaction['reference'] ?? null) === $draft->PAYMENT_REFERENCE || $metadataMatches) {
  349. GuestDeclarationDraft::updateAll(
  350. ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
  351. ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
  352. );
  353. return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
  354. }
  355. throw new BadRequestHttpException('Verified payment does not match this guest order.');
  356. }
  357. if (!$metadataMatches) {
  358. GuestDeclarationDraft::updateAll(
  359. ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
  360. ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
  361. );
  362. return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
  363. }
  364. if ($draft->isExpired()) {
  365. GuestDeclarationDraft::updateAll(
  366. ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
  367. ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
  368. );
  369. return ['status' => GuestDeclarationDraftStatus::MANUAL_REVIEW];
  370. }
  371. $transaction = Yii::$app->db->beginTransaction();
  372. $claimed = false;
  373. try {
  374. if (!GuestDeclarationDraft::claimForProcessing($orderSn)) {
  375. $draft->refresh();
  376. if ($draft->STATUS === GuestDeclarationDraftStatus::COMPLETED) {
  377. $transaction->commit();
  378. return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
  379. }
  380. throw new \RuntimeException('Guest order is already being processed.');
  381. }
  382. $claimed = true;
  383. $draft->refresh();
  384. $payload = $draft->getPayload();
  385. $snapshot = $draft->getOrderSnapshot();
  386. $loop = new ApproachDeclarationLoopForm();
  387. $loop->scenario = 'userDec';
  388. $loop->isGuestDeclaration = true;
  389. $loop->guestOrderSn = $orderSn;
  390. $loop->data = [$payload];
  391. $approachOrder = $loop->add();
  392. if (!$approachOrder instanceof ApproachOrder) {
  393. throw new \RuntimeException('Unable to create the paid registration order.');
  394. }
  395. if (abs((float) $approachOrder->ORDER_AMOUNT - (float) $snapshot['amount']) > 0.000001
  396. || abs((float) $approachOrder->PV - (float) $snapshot['pv']) > 0.000001
  397. ) {
  398. throw new \RuntimeException('Order price changed after payment; manual review is required.');
  399. }
  400. if (isset($approachOrder->USER_NAME) && $approachOrder->USER_NAME !== $payload['insertUserName']) {
  401. throw new \RuntimeException('Created member does not match the guest order.');
  402. }
  403. $verify = new ApproachOrderForm();
  404. $verify->scenario = 'verifyPayStack';
  405. $verify->sn = $orderSn;
  406. $verify->status = Yii::$app->params['orderStatus']['paid']['value'];
  407. $verify->note = [
  408. 'id' => $verifiedTransaction['id'] ?? null,
  409. 'domain' => $verifiedTransaction['domain'] ?? null,
  410. 'status' => $verifiedTransaction['status'],
  411. 'reference' => $verifiedTransaction['reference'],
  412. 'amount' => $verifiedTransaction['amount'],
  413. 'created_at' => $verifiedTransaction['created_at'] ?? null,
  414. 'paid_at' => $verifiedTransaction['paid_at'] ?? null,
  415. 'channel' => $verifiedTransaction['channel'] ?? null,
  416. 'currency' => $verifiedTransaction['currency'],
  417. 'metadata' => $verifiedTransaction['metadata'],
  418. 'email' => $verifiedTransaction['customer']['email'] ?? $verifiedTransaction['email'] ?? '',
  419. ];
  420. $verifiedOrder = $verify->verifyPayStack();
  421. if (!$verifiedOrder) {
  422. throw new \RuntimeException('Unable to finalize the paid registration order.');
  423. }
  424. $draft->USER_ID = $approachOrder->USER_ID;
  425. $draft->PAYLOAD = json_encode(['insertUserName' => $payload['insertUserName']], JSON_UNESCAPED_UNICODE);
  426. $draft->STATUS = GuestDeclarationDraftStatus::COMPLETED;
  427. $draft->PAID_AT = time();
  428. $draft->COMPLETED_AT = time();
  429. $draft->UPDATED_AT = time();
  430. if (!$draft->save(false)) {
  431. throw new \RuntimeException('Unable to complete guest order draft.');
  432. }
  433. $transaction->commit();
  434. return ['status' => GuestDeclarationDraftStatus::COMPLETED, 'userId' => $draft->USER_ID];
  435. } catch (\Throwable $e) {
  436. if ($transaction->isActive) {
  437. $transaction->rollBack();
  438. }
  439. if ($claimed) {
  440. GuestDeclarationDraft::updateAll(
  441. ['STATUS' => GuestDeclarationDraftStatus::MANUAL_REVIEW, 'UPDATED_AT' => time()],
  442. ['AND', ['ORDER_SN' => $orderSn], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT]]
  443. );
  444. }
  445. throw $e;
  446. }
  447. }
  448. public function markPaymentFailed(string $reference, array $verifiedTransaction): void
  449. {
  450. $draft = GuestDeclarationDraft::findOne(['PAYMENT_REFERENCE' => $reference]);
  451. if (!$draft || $draft->STATUS !== GuestDeclarationDraftStatus::PENDING_PAYMENT
  452. || ($verifiedTransaction['status'] ?? null) === 'success'
  453. || (string) ($verifiedTransaction['reference'] ?? '') !== $reference
  454. ) {
  455. return;
  456. }
  457. GuestDeclarationDraft::updateAll(
  458. ['STATUS' => GuestDeclarationDraftStatus::PAYMENT_FAILED, 'PAYMENT_REFERENCE' => null, 'PAYMENT_NOTE' => null, 'UPDATED_AT' => time()],
  459. ['AND', ['ID' => $draft->ID], ['STATUS' => GuestDeclarationDraftStatus::PENDING_PAYMENT], ['PAYMENT_REFERENCE' => $reference]]
  460. );
  461. }
  462. /**
  463. * Require both unguessable draft id and its one-time bearer token.
  464. */
  465. private function loadAuthorizedDraft(string $draftId, string $accessToken): GuestDeclarationDraft
  466. {
  467. $draft = GuestDeclarationDraft::findOne(['ID' => $draftId]);
  468. if (!$draft || !$draft->accessTokenMatches($accessToken)) {
  469. throw new NotFoundHttpException('Guest order draft was not found.');
  470. }
  471. return $draft;
  472. }
  473. }