| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534 |
- <?php
-
- namespace App\Commerce\Shipping\EasyParcel;
-
- use App\Models\EasyParcelAccount;
- use App\Models\Order;
- use App\Models\OrderItem;
- use App\Models\Store;
- use App\Support\MalaysianPhone;
- use Illuminate\Http\Client\ConnectionException;
- use Illuminate\Http\Client\PendingRequest;
- use Illuminate\Http\Client\Response;
- use Illuminate\Support\Arr;
- use Illuminate\Support\Facades\Http;
- use Illuminate\Support\Str;
-
- /**
- * Talks to EasyParcel's Open API for one merchant at a time.
- *
- * Each merchant connects their own EasyParcel account (OAuth): they sign in on EasyParcel and click Allow,
- * and we keep the tokens. Parcels are then quoted and booked on their account and paid from its credit.
- * EasyParcel decides test (sandbox) or live by which account the merchant signs in with.
- */
- final class EasyParcel
- {
- /** Renew the access token this many seconds before it runs out. */
- private const int RENEW_EARLY = 120;
-
- public function __construct(private readonly array $config = []) {}
-
- public static function fromConfig(): self
- {
- return new self((array) config('services.easyparcel'));
- }
-
- /** True once the app's own EasyParcel client ID and secret are in .env.local. */
- public function isConfigured(): bool
- {
- return filled($this->config['client_id'] ?? null) && filled($this->config['client_secret'] ?? null);
- }
-
- public function redirectUri(): string
- {
- return route('easyparcel.callback');
- }
-
- /**
- * The EasyParcel page where the merchant signs in and allows us to use their account.
- * The verifier is kept by the caller and sent back in connect() (PKCE: proves the answer is for this request).
- */
- public function authorizeUrl(string $state, string $verifier): string
- {
- $challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');
-
- return $this->baseUrl().'/oauth/login?'.http_build_query([
- 'response_type' => 'code',
- 'client_id' => $this->config['client_id'] ?? '',
- 'redirect_uri' => $this->redirectUri(),
- 'state' => $state,
- 'code_challenge' => $challenge,
- 'code_challenge_method' => 'S256',
- ]);
- }
-
- /**
- * Swap the code EasyParcel sent back for tokens, and save the connection on the store.
- */
- public function connect(Store $store, string $code, string $verifier): EasyParcelAccount
- {
- $tokens = $this->tokenRequest([
- 'grant_type' => 'authorization_code',
- 'code' => $code,
- 'redirect_uri' => $this->redirectUri(),
- 'code_verifier' => $verifier,
- ]);
-
- $account = $store->easyparcel()->firstOrNew();
- $this->saveTokens($account, $tokens);
-
- // The account's name, so the merchant sees which account is connected. Not needed to work.
- try {
- $info = $this->call($account, 'GET', 'account/get_account_information');
- $account->account_name = Str::limit((string) (Arr::get($info, 'data.account.name') ?? ''), 120, '') ?: null;
- $account->save();
- } catch (EasyParcelException) {
- // Keep the connection; the name is only for show.
- }
-
- return $account;
- }
-
- /**
- * The account's credit balance in sen, or null when EasyParcel does not say.
- */
- public function balance(EasyParcelAccount $account): ?int
- {
- $wallet = Arr::get($this->call($account, 'GET', 'wallet'), 'data.wallet.0.balance');
-
- return is_numeric($wallet) ? (int) round(((float) $wallet) * 100) : null;
- }
-
- /**
- * Courier services for sending this order's parcel, cheapest first.
- *
- * @return list<Quote>
- */
- public function quotes(Store $store, Order $order, Parcel $parcel): array
- {
- $account = $this->accountOf($store);
- $pickup = $this->pickupOf($store);
-
- $answer = $this->call($account, 'POST', 'shipment/quotations', [
- 'shipment' => [[
- 'sender' => ['postcode' => $pickup['postcode'], 'subdivision_code' => StateCodes::for($pickup['state']), 'country' => 'MY'],
- 'receiver' => ['postcode' => $order->shipping_address['postcode'], 'subdivision_code' => StateCodes::for($order->shipping_address['state']), 'country' => 'MY'],
- 'parcel_value' => self::ringgit($order->subtotal - $order->discount_total),
- 'weight' => $parcel->kilograms(),
- 'length' => $parcel->length,
- 'width' => $parcel->width,
- 'height' => $parcel->height,
- ]],
- ]);
-
- $result = Arr::get($answer, 'data.0', []);
- $this->failIfError($result);
-
- $quotes = [];
-
- foreach ((array) Arr::get($result, 'quotations', []) as $quotation) {
- $serviceId = (string) Arr::get($quotation, 'courier.service_id', '');
- // The total includes paid extras (SMS, email, WhatsApp tracking) that we switch off when booking,
- // so the real price is the shipment and its tax.
- $shipping = Arr::get($quotation, 'pricing.shipment_price');
- $price = is_numeric($shipping)
- ? (float) $shipping + (float) (Arr::get($quotation, 'pricing.shipment_tax') ?? 0)
- : Arr::get($quotation, 'pricing.total_amount');
-
- // Services that deliver to a collection point need the shopper to pick one, which checkout does not ask.
- if ($serviceId === '' || ! is_numeric($price) || Arr::get($quotation, 'courier.is_deliver_to_point') === true) {
- continue;
- }
-
- $service = (string) Arr::get($quotation, 'courier.service_name', '');
-
- $quotes[] = new Quote(
- serviceId: $serviceId,
- courier: self::shortName($service, (string) Arr::get($quotation, 'courier.courier_name', '')),
- service: $service,
- logo: Arr::get($quotation, 'courier.courier_logo') ?: null,
- price: (int) round(((float) $price) * 100),
- pickup: (bool) Arr::get($quotation, 'courier.is_pickup', false),
- dropoff: (bool) Arr::get($quotation, 'courier.is_dropoff', false),
- delivery: self::deliveryTime(Arr::get($quotation, 'courier.delivery_duration')),
- note: preg_match('/min\.?\s*(\d+)\s*parcel/i', $service, $match) === 1
- ? __('Pickup needs at least :count parcels', ['count' => $match[1]])
- : null,
- );
- }
-
- usort($quotes, fn (Quote $a, Quote $b) => $a->price <=> $b->price);
-
- return $quotes;
- }
-
- /**
- * Book a courier for the order. EasyParcel takes the price from the merchant's credit.
- * The order is updated with the shipment number, price, label and tracking (when EasyParcel already has them).
- */
- public function book(Store $store, Order $order, Parcel $parcel, string $serviceId, string $collectionDate, ?string $courier = null): void
- {
- $account = $this->accountOf($store);
- $pickup = $this->pickupOf($store);
- $address = $order->shipping_address;
- $order->loadMissing('items');
- $pieces = max(1, (int) $order->items->sum('quantity'));
-
- $answer = $this->call($account, 'POST', 'shipment/submit_orders', [
- 'shipment' => [[
- 'reference' => Str::limit("{$store->name} #{$order->number}", 25, ''),
- 'service_id' => $serviceId,
- 'collection_date' => $collectionDate,
- 'weight' => $parcel->kilograms(),
- 'length' => $parcel->length,
- 'width' => $parcel->width,
- 'height' => $parcel->height,
- 'item' => $order->items->map(fn (OrderItem $item) => [
- 'content' => Str::limit($item->name, 35, ''),
- 'weight' => round(max($parcel->kilograms() / $pieces, 0.01), 2),
- 'length' => $parcel->length,
- 'width' => $parcel->width,
- 'height' => $parcel->height,
- 'currency_code' => 'MYR',
- 'value' => self::ringgit($item->unit_price),
- 'quantity' => $item->quantity,
- ])->values()->all(),
- 'sender' => [
- 'name' => $pickup['name'],
- 'phone_number_country_code' => 'MY',
- 'phone_number' => self::localPhone($pickup['phone']),
- 'email' => $store->user->email,
- 'address_1' => $pickup['line1'],
- 'address_2' => $pickup['line2'] ?? '',
- 'postcode' => $pickup['postcode'],
- 'city' => $pickup['city'],
- 'subdivision_code' => StateCodes::for($pickup['state']),
- 'country_code' => 'MY',
- ],
- 'receiver' => [
- 'name' => $order->customer_name,
- 'phone_number_country_code' => 'MY',
- 'phone_number' => self::localPhone($order->customer_phone),
- 'email' => $order->customer_email,
- 'address_1' => $address['line1'],
- 'address_2' => $address['line2'] ?? '',
- 'postcode' => $address['postcode'],
- 'city' => $address['city'],
- 'subdivision_code' => StateCodes::for($address['state']),
- 'country_code' => 'MY',
- ],
- // Paid extras stay off; the shopper gets our own "on its way" email with the tracking link.
- 'feature' => ['sms_tracking' => false, 'email_tracking' => false, 'whatsapp_tracking' => false],
- ]],
- ]);
-
- $result = Arr::get($answer, 'data.0', []);
- $this->failIfError($result);
- $shipment = Arr::get($result, 'shipments.0', []);
- $this->failIfError($shipment);
-
- $number = (string) Arr::get($shipment, 'shipment_number', '');
-
- if ($number === '') {
- throw new EasyParcelException(self::messageOf($result) ?? __('EasyParcel did not confirm the booking. Check your EasyParcel account before trying again.'));
- }
-
- $paid = Arr::get($shipment, 'pricing_breakdown.total_paid_amount');
-
- $order->shipment_number = $number;
- $order->shipment_order_number = Arr::get($result, 'order_details.order_number') ?: null;
- $order->shipment_cost = is_numeric($paid) ? (int) round(((float) $paid) * 100) : null;
- // The short name the merchant picked ("J&T Express"), not the company's full name.
- $order->shipping_courier = Str::limit((string) ($courier ?: Arr::get($shipment, 'courier') ?: 'EasyParcel'), 60, '');
- $this->takeLabel($order, $shipment);
- $order->save();
- }
-
- /**
- * Ask EasyParcel again for a booked parcel's label and tracking number, which some couriers give a little later.
- */
- public function refreshLabel(Store $store, Order $order): void
- {
- $answer = $this->call($this->accountOf($store), 'POST', 'shipment/details', ['shipment_number' => $order->shipment_number]);
- $data = (array) Arr::get($answer, 'data', []);
- $details = Arr::get($data, '0.shipment_details') ?? Arr::get($data, 'shipment_details') ?? Arr::get($data, '0') ?? $data;
-
- $this->takeLabel($order, is_array($details) ? $details : []);
- $order->save();
- }
-
- /**
- * @param array<string, mixed> $shipment
- */
- private function takeLabel(Order $order, array $shipment): void
- {
- $awb = trim((string) (Arr::get($shipment, 'awb_number') ?? ''));
- $label = (string) (Arr::get($shipment, 'awb_url') ?: Arr::get($shipment, 'awb_urls_by_format.A4') ?: '');
- $tracking = (string) (Arr::get($shipment, 'tracking_url') ?? '');
-
- if ($awb !== '') {
- $order->tracking_number = Str::limit($awb, 80, '');
- }
-
- if (str_starts_with($label, 'https://')) {
- $order->label_url = $label;
- }
-
- if (str_starts_with($tracking, 'https://')) {
- $order->tracking_url = $tracking;
- }
- }
-
- /**
- * One call to the Open API on the merchant's account. Renews the access token when it has run out.
- *
- * @param array<string, mixed> $body
- * @return array<string, mixed>
- */
- private function call(EasyParcelAccount $account, string $method, string $path, array $body = []): array
- {
- if ($account->expires_at !== null && $account->expires_at->isBefore(now()->addSeconds(self::RENEW_EARLY))) {
- $this->renew($account);
- }
-
- $response = $this->send($account, $method, $path, $body);
-
- if ($response->status() === 401) {
- $this->renew($account);
- $response = $this->send($account, $method, $path, $body);
-
- if ($response->status() === 401) {
- throw new EasyParcelException(__('Your EasyParcel connection has expired. Connect EasyParcel again in Settings.'), EasyParcelException::DISCONNECTED);
- }
- }
-
- if ($response->status() === 429) {
- throw new EasyParcelException(__('EasyParcel is busy. Please wait a minute and try again.'));
- }
-
- $json = (array) $response->json();
-
- if ($response->failed()) {
- throw new EasyParcelException(self::messageOf($json) ?? __('EasyParcel could not do this right now (error :code). Please try again.', ['code' => $response->status()]));
- }
-
- return $json;
- }
-
- /**
- * @param array<string, mixed> $body
- */
- private function send(EasyParcelAccount $account, string $method, string $path, array $body): Response
- {
- $url = $this->baseUrl().'/open_api/'.($this->config['api_version'] ?? '2026-09').'/'.$path;
-
- try {
- $request = $this->http()->withToken($account->access_token);
-
- return $method === 'GET' ? $request->get($url) : $request->post($url, $body);
- } catch (ConnectionException) {
- throw new EasyParcelException(__('Could not reach EasyParcel. Check your internet connection and try again.'));
- }
- }
-
- private function renew(EasyParcelAccount $account): void
- {
- if (blank($account->refresh_token)) {
- throw new EasyParcelException(__('Your EasyParcel connection has expired. Connect EasyParcel again in Settings.'), EasyParcelException::DISCONNECTED);
- }
-
- try {
- $tokens = $this->tokenRequest(['grant_type' => 'refresh_token', 'refresh_token' => $account->refresh_token]);
- } catch (EasyParcelException $e) {
- throw new EasyParcelException(__('Your EasyParcel connection has expired. Connect EasyParcel again in Settings.'), EasyParcelException::DISCONNECTED, $e);
- }
-
- $this->saveTokens($account, $tokens);
- }
-
- /**
- * @param array<string, string> $form
- * @return array<string, mixed>
- */
- private function tokenRequest(array $form): array
- {
- if (! $this->isConfigured()) {
- throw new EasyParcelException(__('EasyParcel is not set up on this app yet.'));
- }
-
- try {
- $response = $this->http()
- ->withBasicAuth((string) $this->config['client_id'], (string) $this->config['client_secret'])
- ->asForm()
- ->post($this->baseUrl().'/oauth/token', $form);
- } catch (ConnectionException) {
- throw new EasyParcelException(__('Could not reach EasyParcel. Check your internet connection and try again.'));
- }
-
- $json = (array) $response->json();
- // Some answers wrap the tokens in "data".
- $tokens = isset($json['access_token']) ? $json : (array) ($json['data'] ?? []);
-
- if ($response->failed() || blank($tokens['access_token'] ?? null)) {
- throw new EasyParcelException(self::messageOf($json) ?? __('EasyParcel did not accept the connection. Please try again.'));
- }
-
- return $tokens;
- }
-
- /**
- * @param array<string, mixed> $tokens
- */
- private function saveTokens(EasyParcelAccount $account, array $tokens): void
- {
- $account->access_token = (string) $tokens['access_token'];
- // Keep the old refresh token when EasyParcel does not send a new one.
- $account->refresh_token = filled($tokens['refresh_token'] ?? null) ? (string) $tokens['refresh_token'] : $account->refresh_token;
- $account->expires_at = is_numeric($tokens['expires_in'] ?? null) ? now()->addSeconds((int) $tokens['expires_in']) : null;
- $account->save();
- }
-
- private function accountOf(Store $store): EasyParcelAccount
- {
- return $store->easyparcel ?? throw new EasyParcelException(__('Connect EasyParcel in Settings first.'), EasyParcelException::DISCONNECTED);
- }
-
- /**
- * @return array{name: string, phone: string, line1: string, line2: string|null, city: string, postcode: string, state: string}
- */
- private function pickupOf(Store $store): array
- {
- return $store->pickup_address ?? throw new EasyParcelException(__('Add your pickup address in Settings first.'));
- }
-
- /**
- * @param array<string, mixed> $result
- */
- private function failIfError(array $result): void
- {
- if (($result['status'] ?? null) !== 'error') {
- return;
- }
-
- throw new EasyParcelException(self::messageOf($result) ?? __('EasyParcel could not do this. Please check the details and try again.'));
- }
-
- /**
- * The most useful sentence in an EasyParcel error answer.
- *
- * @param array<string, mixed> $json
- */
- private static function messageOf(array $json): ?string
- {
- // Errors come as strings, as {code, message} objects, or as lists of those inside a list.
- $errors = [];
- $list = is_array($json['errors'] ?? null) ? $json['errors'] : [];
- array_walk_recursive($list, function (mixed $value, mixed $key) use (&$errors) {
- if (is_string($value) && ($key === 'message' || is_int($key)) && trim($value) !== '') {
- $errors[] = trim($value);
- }
- });
-
- // Not enough credit: say how much the parcel needs, so the merchant knows what to top up.
- foreach (self::errorObjects($json['errors'] ?? []) as $error) {
- if (($error['code'] ?? null) === 'InsufficientCreditBalance') {
- $needed = Arr::get($error, 'data.total_amount');
-
- return is_numeric($needed)
- ? __('Not enough EasyParcel credit: this parcel needs RM :amount. Top up your EasyParcel account and try again.', ['amount' => number_format((float) $needed, 2)])
- : __('Not enough EasyParcel credit. Top up your EasyParcel account and try again.');
- }
- }
-
- if ($errors !== []) {
- return 'EasyParcel: '.Str::limit(implode(' ', array_unique($errors)), 300);
- }
-
- foreach (['message', 'error_description', 'error'] as $key) {
- if (is_string($json[$key] ?? null) && trim($json[$key]) !== '') {
- return 'EasyParcel: '.Str::limit(trim($json[$key]), 300);
- }
- }
-
- return null;
- }
-
- /**
- * Every {code, message} object in an error list, however deeply it is wrapped.
- *
- * @return list<array<string, mixed>>
- */
- private static function errorObjects(mixed $errors): array
- {
- if (! is_array($errors)) {
- return [];
- }
-
- if (isset($errors['message']) || isset($errors['code'])) {
- return [$errors];
- }
-
- return array_merge([], ...array_map(self::errorObjects(...), array_values($errors)));
- }
-
- /**
- * "J&T Express (Pick Up) (From Door to Door)" becomes "J&T Express". The company name is the fallback.
- */
- private static function shortName(string $service, string $company): string
- {
- $short = trim((string) preg_replace(['/\((?:[^()]|\([^()]*\))*\)/', '/\s+/'], ['', ' '], $service));
-
- if ($short !== '') {
- return $short;
- }
-
- $company = trim((string) preg_replace('/\s*(\((?:Malaysia|M)\)|Sdn\.?\s*Bhd\.?|Berhad)\s*/i', ' ', $company));
-
- return $company !== '' ? preg_replace('/\s+/', ' ', $company) : 'Courier';
- }
-
- /**
- * EasyParcel sends the delivery time as {"type":"days","value":"3"} (sometimes as a JSON string), or nothing.
- */
- private static function deliveryTime(mixed $duration): ?string
- {
- if (is_string($duration)) {
- $decoded = json_decode($duration, true);
- $duration = is_array($decoded) ? $decoded : $duration;
- }
-
- if (is_array($duration) && is_numeric($duration['value'] ?? null) && ($duration['type'] ?? 'days') === 'days') {
- $days = (int) $duration['value'];
-
- return $days <= 1 ? __('Next day') : __('About :count days', ['count' => $days]);
- }
-
- return is_string($duration) && trim($duration) !== '' ? Str::limit(trim($duration), 40) : null;
- }
-
- private function http(): PendingRequest
- {
- // Quotes can take up to a minute when couriers are asked live.
- return Http::acceptJson()->timeout(70);
- }
-
- private function baseUrl(): string
- {
- return rtrim((string) ($this->config['base_url'] ?? 'https://api.easyparcel.com'), '/');
- }
-
- private static function ringgit(int $sen): float
- {
- return round($sen / 100, 2);
- }
-
- /**
- * EasyParcel wants the number without Malaysia's 60, such as 123456789.
- */
- private static function localPhone(string $phone): string
- {
- $normalized = MalaysianPhone::normalize($phone);
-
- return $normalized !== null ? substr($normalized, 2) : preg_replace('/\D/', '', $phone);
- }
- }
|