GuestDeclarationOrderService.php 28 KB

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