AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

EasyParcel.php 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. <?php
  2. namespace App\Commerce\Shipping\EasyParcel;
  3. use App\Models\EasyParcelAccount;
  4. use App\Models\Order;
  5. use App\Models\OrderItem;
  6. use App\Models\Store;
  7. use App\Support\MalaysianPhone;
  8. use Illuminate\Http\Client\ConnectionException;
  9. use Illuminate\Http\Client\PendingRequest;
  10. use Illuminate\Http\Client\Response;
  11. use Illuminate\Support\Arr;
  12. use Illuminate\Support\Facades\Http;
  13. use Illuminate\Support\Str;
  14. /**
  15. * Talks to EasyParcel's Open API for one merchant at a time.
  16. *
  17. * Each merchant connects their own EasyParcel account (OAuth): they sign in on EasyParcel and click Allow,
  18. * and we keep the tokens. Parcels are then quoted and booked on their account and paid from its credit.
  19. * EasyParcel decides test (sandbox) or live by which account the merchant signs in with.
  20. */
  21. final class EasyParcel
  22. {
  23. /** Renew the access token this many seconds before it runs out. */
  24. private const int RENEW_EARLY = 120;
  25. public function __construct(private readonly array $config = []) {}
  26. public static function fromConfig(): self
  27. {
  28. return new self((array) config('services.easyparcel'));
  29. }
  30. /** True once the app's own EasyParcel client ID and secret are in .env.local. */
  31. public function isConfigured(): bool
  32. {
  33. return filled($this->config['client_id'] ?? null) && filled($this->config['client_secret'] ?? null);
  34. }
  35. public function redirectUri(): string
  36. {
  37. return route('easyparcel.callback');
  38. }
  39. /**
  40. * The EasyParcel page where the merchant signs in and allows us to use their account.
  41. * The verifier is kept by the caller and sent back in connect() (PKCE: proves the answer is for this request).
  42. */
  43. public function authorizeUrl(string $state, string $verifier): string
  44. {
  45. $challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
  46. return $this->baseUrl().'/oauth/login?'.http_build_query([
  47. 'response_type' => 'code',
  48. 'client_id' => $this->config['client_id'] ?? '',
  49. 'redirect_uri' => $this->redirectUri(),
  50. 'state' => $state,
  51. 'code_challenge' => $challenge,
  52. 'code_challenge_method' => 'S256',
  53. ]);
  54. }
  55. /**
  56. * Swap the code EasyParcel sent back for tokens, and save the connection on the store.
  57. */
  58. public function connect(Store $store, string $code, string $verifier): EasyParcelAccount
  59. {
  60. $tokens = $this->tokenRequest([
  61. 'grant_type' => 'authorization_code',
  62. 'code' => $code,
  63. 'redirect_uri' => $this->redirectUri(),
  64. 'code_verifier' => $verifier,
  65. ]);
  66. $account = $store->easyparcel()->firstOrNew();
  67. $this->saveTokens($account, $tokens);
  68. // The account's name, so the merchant sees which account is connected. Not needed to work.
  69. try {
  70. $info = $this->call($account, 'GET', 'account/get_account_information');
  71. $account->account_name = Str::limit((string) (Arr::get($info, 'data.account.name') ?? ''), 120, '') ?: null;
  72. $account->save();
  73. } catch (EasyParcelException) {
  74. // Keep the connection; the name is only for show.
  75. }
  76. return $account;
  77. }
  78. /**
  79. * The account's credit balance in sen, or null when EasyParcel does not say.
  80. */
  81. public function balance(EasyParcelAccount $account): ?int
  82. {
  83. $wallet = Arr::get($this->call($account, 'GET', 'wallet'), 'data.wallet.0.balance');
  84. return is_numeric($wallet) ? (int) round(((float) $wallet) * 100) : null;
  85. }
  86. /**
  87. * Courier services for sending this order's parcel, cheapest first.
  88. *
  89. * @return list<Quote>
  90. */
  91. public function quotes(Store $store, Order $order, Parcel $parcel): array
  92. {
  93. $account = $this->accountOf($store);
  94. $pickup = $this->pickupOf($store);
  95. $answer = $this->call($account, 'POST', 'shipment/quotations', [
  96. 'shipment' => [[
  97. 'sender' => ['postcode' => $pickup['postcode'], 'subdivision_code' => StateCodes::for($pickup['state']), 'country' => 'MY'],
  98. 'receiver' => ['postcode' => $order->shipping_address['postcode'], 'subdivision_code' => StateCodes::for($order->shipping_address['state']), 'country' => 'MY'],
  99. 'parcel_value' => self::ringgit($order->subtotal - $order->discount_total),
  100. 'weight' => $parcel->kilograms(),
  101. 'length' => $parcel->length,
  102. 'width' => $parcel->width,
  103. 'height' => $parcel->height,
  104. ]],
  105. ]);
  106. $result = Arr::get($answer, 'data.0', []);
  107. $this->failIfError($result);
  108. $quotes = [];
  109. foreach ((array) Arr::get($result, 'quotations', []) as $quotation) {
  110. $serviceId = (string) Arr::get($quotation, 'courier.service_id', '');
  111. // The total includes paid extras (SMS, email, WhatsApp tracking) that we switch off when booking,
  112. // so the real price is the shipment and its tax.
  113. $shipping = Arr::get($quotation, 'pricing.shipment_price');
  114. $price = is_numeric($shipping)
  115. ? (float) $shipping + (float) (Arr::get($quotation, 'pricing.shipment_tax') ?? 0)
  116. : Arr::get($quotation, 'pricing.total_amount');
  117. // Services that deliver to a collection point need the shopper to pick one, which checkout does not ask.
  118. if ($serviceId === '' || ! is_numeric($price) || Arr::get($quotation, 'courier.is_deliver_to_point') === true) {
  119. continue;
  120. }
  121. $service = (string) Arr::get($quotation, 'courier.service_name', '');
  122. $quotes[] = new Quote(
  123. serviceId: $serviceId,
  124. courier: self::shortName($service, (string) Arr::get($quotation, 'courier.courier_name', '')),
  125. service: $service,
  126. logo: Arr::get($quotation, 'courier.courier_logo') ?: null,
  127. price: (int) round(((float) $price) * 100),
  128. pickup: (bool) Arr::get($quotation, 'courier.is_pickup', false),
  129. dropoff: (bool) Arr::get($quotation, 'courier.is_dropoff', false),
  130. delivery: self::deliveryTime(Arr::get($quotation, 'courier.delivery_duration')),
  131. note: preg_match('/min\.?\s*(\d+)\s*parcel/i', $service, $match) === 1
  132. ? __('Pickup needs at least :count parcels', ['count' => $match[1]])
  133. : null,
  134. );
  135. }
  136. usort($quotes, fn (Quote $a, Quote $b) => $a->price <=> $b->price);
  137. return $quotes;
  138. }
  139. /**
  140. * Book a courier for the order. EasyParcel takes the price from the merchant's credit.
  141. * The order is updated with the shipment number, price, label and tracking (when EasyParcel already has them).
  142. */
  143. public function book(Store $store, Order $order, Parcel $parcel, string $serviceId, string $collectionDate, ?string $courier = null): void
  144. {
  145. $account = $this->accountOf($store);
  146. $pickup = $this->pickupOf($store);
  147. $address = $order->shipping_address;
  148. $order->loadMissing('items');
  149. $pieces = max(1, (int) $order->items->sum('quantity'));
  150. $answer = $this->call($account, 'POST', 'shipment/submit_orders', [
  151. 'shipment' => [[
  152. 'reference' => Str::limit("{$store->name} #{$order->number}", 25, ''),
  153. 'service_id' => $serviceId,
  154. 'collection_date' => $collectionDate,
  155. 'weight' => $parcel->kilograms(),
  156. 'length' => $parcel->length,
  157. 'width' => $parcel->width,
  158. 'height' => $parcel->height,
  159. 'item' => $order->items->map(fn (OrderItem $item) => [
  160. 'content' => Str::limit($item->name, 35, ''),
  161. 'weight' => round(max($parcel->kilograms() / $pieces, 0.01), 2),
  162. 'length' => $parcel->length,
  163. 'width' => $parcel->width,
  164. 'height' => $parcel->height,
  165. 'currency_code' => 'MYR',
  166. 'value' => self::ringgit($item->unit_price),
  167. 'quantity' => $item->quantity,
  168. ])->values()->all(),
  169. 'sender' => [
  170. 'name' => $pickup['name'],
  171. 'phone_number_country_code' => 'MY',
  172. 'phone_number' => self::localPhone($pickup['phone']),
  173. 'email' => $store->user->email,
  174. 'address_1' => $pickup['line1'],
  175. 'address_2' => $pickup['line2'] ?? '',
  176. 'postcode' => $pickup['postcode'],
  177. 'city' => $pickup['city'],
  178. 'subdivision_code' => StateCodes::for($pickup['state']),
  179. 'country_code' => 'MY',
  180. ],
  181. 'receiver' => [
  182. 'name' => $order->customer_name,
  183. 'phone_number_country_code' => 'MY',
  184. 'phone_number' => self::localPhone($order->customer_phone),
  185. 'email' => $order->customer_email,
  186. 'address_1' => $address['line1'],
  187. 'address_2' => $address['line2'] ?? '',
  188. 'postcode' => $address['postcode'],
  189. 'city' => $address['city'],
  190. 'subdivision_code' => StateCodes::for($address['state']),
  191. 'country_code' => 'MY',
  192. ],
  193. // Paid extras stay off; the shopper gets our own "on its way" email with the tracking link.
  194. 'feature' => ['sms_tracking' => false, 'email_tracking' => false, 'whatsapp_tracking' => false],
  195. ]],
  196. ]);
  197. $result = Arr::get($answer, 'data.0', []);
  198. $this->failIfError($result);
  199. $shipment = Arr::get($result, 'shipments.0', []);
  200. $this->failIfError($shipment);
  201. $number = (string) Arr::get($shipment, 'shipment_number', '');
  202. if ($number === '') {
  203. throw new EasyParcelException(self::messageOf($result) ?? __('EasyParcel did not confirm the booking. Check your EasyParcel account before trying again.'));
  204. }
  205. $paid = Arr::get($shipment, 'pricing_breakdown.total_paid_amount');
  206. $order->shipment_number = $number;
  207. $order->shipment_order_number = Arr::get($result, 'order_details.order_number') ?: null;
  208. $order->shipment_cost = is_numeric($paid) ? (int) round(((float) $paid) * 100) : null;
  209. // The short name the merchant picked ("J&T Express"), not the company's full name.
  210. $order->shipping_courier = Str::limit((string) ($courier ?: Arr::get($shipment, 'courier') ?: 'EasyParcel'), 60, '');
  211. $this->takeLabel($order, $shipment);
  212. $order->save();
  213. }
  214. /**
  215. * Ask EasyParcel again for a booked parcel's label and tracking number, which some couriers give a little later.
  216. */
  217. public function refreshLabel(Store $store, Order $order): void
  218. {
  219. $answer = $this->call($this->accountOf($store), 'POST', 'shipment/details', ['shipment_number' => $order->shipment_number]);
  220. $data = (array) Arr::get($answer, 'data', []);
  221. $details = Arr::get($data, '0.shipment_details') ?? Arr::get($data, 'shipment_details') ?? Arr::get($data, '0') ?? $data;
  222. $this->takeLabel($order, is_array($details) ? $details : []);
  223. $order->save();
  224. }
  225. /**
  226. * @param array<string, mixed> $shipment
  227. */
  228. private function takeLabel(Order $order, array $shipment): void
  229. {
  230. $awb = trim((string) (Arr::get($shipment, 'awb_number') ?? ''));
  231. $label = (string) (Arr::get($shipment, 'awb_url') ?: Arr::get($shipment, 'awb_urls_by_format.A4') ?: '');
  232. $tracking = (string) (Arr::get($shipment, 'tracking_url') ?? '');
  233. if ($awb !== '') {
  234. $order->tracking_number = Str::limit($awb, 80, '');
  235. }
  236. if (str_starts_with($label, 'https://')) {
  237. $order->label_url = $label;
  238. }
  239. if (str_starts_with($tracking, 'https://')) {
  240. $order->tracking_url = $tracking;
  241. }
  242. }
  243. /**
  244. * One call to the Open API on the merchant's account. Renews the access token when it has run out.
  245. *
  246. * @param array<string, mixed> $body
  247. * @return array<string, mixed>
  248. */
  249. private function call(EasyParcelAccount $account, string $method, string $path, array $body = []): array
  250. {
  251. if ($account->expires_at !== null && $account->expires_at->isBefore(now()->addSeconds(self::RENEW_EARLY))) {
  252. $this->renew($account);
  253. }
  254. $response = $this->send($account, $method, $path, $body);
  255. if ($response->status() === 401) {
  256. $this->renew($account);
  257. $response = $this->send($account, $method, $path, $body);
  258. if ($response->status() === 401) {
  259. throw new EasyParcelException(__('Your EasyParcel connection has expired. Connect EasyParcel again in Settings.'), EasyParcelException::DISCONNECTED);
  260. }
  261. }
  262. if ($response->status() === 429) {
  263. throw new EasyParcelException(__('EasyParcel is busy. Please wait a minute and try again.'));
  264. }
  265. $json = (array) $response->json();
  266. if ($response->failed()) {
  267. throw new EasyParcelException(self::messageOf($json) ?? __('EasyParcel could not do this right now (error :code). Please try again.', ['code' => $response->status()]));
  268. }
  269. return $json;
  270. }
  271. /**
  272. * @param array<string, mixed> $body
  273. */
  274. private function send(EasyParcelAccount $account, string $method, string $path, array $body): Response
  275. {
  276. $url = $this->baseUrl().'/open_api/'.($this->config['api_version'] ?? '2026-09').'/'.$path;
  277. try {
  278. $request = $this->http()->withToken($account->access_token);
  279. return $method === 'GET' ? $request->get($url) : $request->post($url, $body);
  280. } catch (ConnectionException) {
  281. throw new EasyParcelException(__('Could not reach EasyParcel. Check your internet connection and try again.'));
  282. }
  283. }
  284. private function renew(EasyParcelAccount $account): void
  285. {
  286. if (blank($account->refresh_token)) {
  287. throw new EasyParcelException(__('Your EasyParcel connection has expired. Connect EasyParcel again in Settings.'), EasyParcelException::DISCONNECTED);
  288. }
  289. try {
  290. $tokens = $this->tokenRequest(['grant_type' => 'refresh_token', 'refresh_token' => $account->refresh_token]);
  291. } catch (EasyParcelException $e) {
  292. throw new EasyParcelException(__('Your EasyParcel connection has expired. Connect EasyParcel again in Settings.'), EasyParcelException::DISCONNECTED, $e);
  293. }
  294. $this->saveTokens($account, $tokens);
  295. }
  296. /**
  297. * @param array<string, string> $form
  298. * @return array<string, mixed>
  299. */
  300. private function tokenRequest(array $form): array
  301. {
  302. if (! $this->isConfigured()) {
  303. throw new EasyParcelException(__('EasyParcel is not set up on this app yet.'));
  304. }
  305. try {
  306. $response = $this->http()
  307. ->withBasicAuth((string) $this->config['client_id'], (string) $this->config['client_secret'])
  308. ->asForm()
  309. ->post($this->baseUrl().'/oauth/token', $form);
  310. } catch (ConnectionException) {
  311. throw new EasyParcelException(__('Could not reach EasyParcel. Check your internet connection and try again.'));
  312. }
  313. $json = (array) $response->json();
  314. // Some answers wrap the tokens in "data".
  315. $tokens = isset($json['access_token']) ? $json : (array) ($json['data'] ?? []);
  316. if ($response->failed() || blank($tokens['access_token'] ?? null)) {
  317. throw new EasyParcelException(self::messageOf($json) ?? __('EasyParcel did not accept the connection. Please try again.'));
  318. }
  319. return $tokens;
  320. }
  321. /**
  322. * @param array<string, mixed> $tokens
  323. */
  324. private function saveTokens(EasyParcelAccount $account, array $tokens): void
  325. {
  326. $account->access_token = (string) $tokens['access_token'];
  327. // Keep the old refresh token when EasyParcel does not send a new one.
  328. $account->refresh_token = filled($tokens['refresh_token'] ?? null) ? (string) $tokens['refresh_token'] : $account->refresh_token;
  329. $account->expires_at = is_numeric($tokens['expires_in'] ?? null) ? now()->addSeconds((int) $tokens['expires_in']) : null;
  330. $account->save();
  331. }
  332. private function accountOf(Store $store): EasyParcelAccount
  333. {
  334. return $store->easyparcel ?? throw new EasyParcelException(__('Connect EasyParcel in Settings first.'), EasyParcelException::DISCONNECTED);
  335. }
  336. /**
  337. * @return array{name: string, phone: string, line1: string, line2: string|null, city: string, postcode: string, state: string}
  338. */
  339. private function pickupOf(Store $store): array
  340. {
  341. return $store->pickup_address ?? throw new EasyParcelException(__('Add your pickup address in Settings first.'));
  342. }
  343. /**
  344. * @param array<string, mixed> $result
  345. */
  346. private function failIfError(array $result): void
  347. {
  348. if (($result['status'] ?? null) !== 'error') {
  349. return;
  350. }
  351. throw new EasyParcelException(self::messageOf($result) ?? __('EasyParcel could not do this. Please check the details and try again.'));
  352. }
  353. /**
  354. * The most useful sentence in an EasyParcel error answer.
  355. *
  356. * @param array<string, mixed> $json
  357. */
  358. private static function messageOf(array $json): ?string
  359. {
  360. // Errors come as strings, as {code, message} objects, or as lists of those inside a list.
  361. $errors = [];
  362. $list = is_array($json['errors'] ?? null) ? $json['errors'] : [];
  363. array_walk_recursive($list, function (mixed $value, mixed $key) use (&$errors) {
  364. if (is_string($value) && ($key === 'message' || is_int($key)) && trim($value) !== '') {
  365. $errors[] = trim($value);
  366. }
  367. });
  368. // Not enough credit: say how much the parcel needs, so the merchant knows what to top up.
  369. foreach (self::errorObjects($json['errors'] ?? []) as $error) {
  370. if (($error['code'] ?? null) === 'InsufficientCreditBalance') {
  371. $needed = Arr::get($error, 'data.total_amount');
  372. return is_numeric($needed)
  373. ? __('Not enough EasyParcel credit: this parcel needs RM :amount. Top up your EasyParcel account and try again.', ['amount' => number_format((float) $needed, 2)])
  374. : __('Not enough EasyParcel credit. Top up your EasyParcel account and try again.');
  375. }
  376. }
  377. if ($errors !== []) {
  378. return 'EasyParcel: '.Str::limit(implode(' ', array_unique($errors)), 300);
  379. }
  380. foreach (['message', 'error_description', 'error'] as $key) {
  381. if (is_string($json[$key] ?? null) && trim($json[$key]) !== '') {
  382. return 'EasyParcel: '.Str::limit(trim($json[$key]), 300);
  383. }
  384. }
  385. return null;
  386. }
  387. /**
  388. * Every {code, message} object in an error list, however deeply it is wrapped.
  389. *
  390. * @return list<array<string, mixed>>
  391. */
  392. private static function errorObjects(mixed $errors): array
  393. {
  394. if (! is_array($errors)) {
  395. return [];
  396. }
  397. if (isset($errors['message']) || isset($errors['code'])) {
  398. return [$errors];
  399. }
  400. return array_merge([], ...array_map(self::errorObjects(...), array_values($errors)));
  401. }
  402. /**
  403. * "J&T Express (Pick Up) (From Door to Door)" becomes "J&T Express". The company name is the fallback.
  404. */
  405. private static function shortName(string $service, string $company): string
  406. {
  407. $short = trim((string) preg_replace(['/\((?:[^()]|\([^()]*\))*\)/', '/\s+/'], ['', ' '], $service));
  408. if ($short !== '') {
  409. return $short;
  410. }
  411. $company = trim((string) preg_replace('/\s*(\((?:Malaysia|M)\)|Sdn\.?\s*Bhd\.?|Berhad)\s*/i', ' ', $company));
  412. return $company !== '' ? preg_replace('/\s+/', ' ', $company) : 'Courier';
  413. }
  414. /**
  415. * EasyParcel sends the delivery time as {"type":"days","value":"3"} (sometimes as a JSON string), or nothing.
  416. */
  417. private static function deliveryTime(mixed $duration): ?string
  418. {
  419. if (is_string($duration)) {
  420. $decoded = json_decode($duration, true);
  421. $duration = is_array($decoded) ? $decoded : $duration;
  422. }
  423. if (is_array($duration) && is_numeric($duration['value'] ?? null) && ($duration['type'] ?? 'days') === 'days') {
  424. $days = (int) $duration['value'];
  425. return $days <= 1 ? __('Next day') : __('About :count days', ['count' => $days]);
  426. }
  427. return is_string($duration) && trim($duration) !== '' ? Str::limit(trim($duration), 40) : null;
  428. }
  429. private function http(): PendingRequest
  430. {
  431. // Quotes can take up to a minute when couriers are asked live.
  432. return Http::acceptJson()->timeout(70);
  433. }
  434. private function baseUrl(): string
  435. {
  436. return rtrim((string) ($this->config['base_url'] ?? 'https://api.easyparcel.com'), '/');
  437. }
  438. private static function ringgit(int $sen): float
  439. {
  440. return round($sen / 100, 2);
  441. }
  442. /**
  443. * EasyParcel wants the number without Malaysia's 60, such as 123456789.
  444. */
  445. private static function localPhone(string $phone): string
  446. {
  447. $normalized = MalaysianPhone::normalize($phone);
  448. return $normalized !== null ? substr($normalized, 2) : preg_replace('/\D/', '', $phone);
  449. }
  450. }