GuestDeclarationOrderService.php 27 KB

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