import { Provide } from "@midwayjs/core"; import { Config } from '@midwayjs/decorator'; import axios, { AxiosRequestConfig } from 'axios'; @Provide() export class UniExpressService { @Config('uniExpress.url') url; @Config('uniExpress.clientId') clientId; @Config('uniExpress.clientSecret') cliientSecret; @Config('uniExpress.customerNo') customerNo; async getToken() { const config: AxiosRequestConfig = { method: 'POST', url: `${this.url}/storeauth/customertoken`, data: { 'grant_type': 'client_credentials', 'client_id': this.clientId, 'client_secret': this.cliientSecret } }; const tokenBody = await axios.request(config); return tokenBody.data.data.access_token; } async getRates(data: any) { try { const requiredKeys = { customer_no: this.customerNo, pickup_warehouse: 1 }; const body = { ...requiredKeys, ...data }; const token = await this.getToken(); const config: AxiosRequestConfig= { method: 'POST', headers: { 'Authorization': `Bearer ${token}` }, url: `${this.url}/orders/estimateshipping`, data: body }; return (await axios.request(config)).data; } catch (error) { console.log(error); } } async createShipment( data: any ) { try { const requiredKeys = { customer_no: this.customerNo, pickup_warehouse: 1 }; const body = { ...requiredKeys, ...data }; const token = await this.getToken(); const config: AxiosRequestConfig= { method: 'POST', headers: { 'Authorization': `Bearer ${token}` }, url: `${this.url}/orders/createbusinessorder`, data: body }; const req = await axios.request(config); const res = req.data; return res; } catch (error) { console.log(error); } } async deleteShipment(tno: string) { const body = { tno }; const token = await this.getToken(); const config: AxiosRequestConfig= { method: 'POST', headers: { 'Authorization': `Bearer ${token}` }, url: `${this.url}/orders/cancelorder`, data: body }; return await axios.request(config); } async getLabel(tracking_number: string) { const body = { packageId: tracking_number }; const token = await this.getToken(); const config: AxiosRequestConfig= { method: 'POST', headers: { 'Authorization': `Bearer ${token}` }, url: `${this.url}/orders/printlabel`, data: body }; return await axios.request(config); } async getOrdersByDate(from: string, to: string, page: number = 1, perPage: number = 100) { try { const token = await this.getToken(); const config: AxiosRequestConfig= { method: 'GET', headers: { 'Authorization': `Bearer ${token}` }, params: { from, to, page, perPage } }; const res = (await axios.request(config)).data; return res; } catch (error) { console.log(error); } } }