80 lines
2.3 KiB
JavaScript
80 lines
2.3 KiB
JavaScript
const axios = require('axios');
|
|
|
|
class PrintfulSupplier {
|
|
constructor({ apiKey, storeId }) {
|
|
this.apiKey = apiKey;
|
|
this.storeId = storeId;
|
|
this.baseUrl = 'https://api.printful.com/v2';
|
|
}
|
|
|
|
buildRecipient(customer, shipping) {
|
|
const address = (shipping && shipping.address) || shipping || {};
|
|
const name =
|
|
customer?.name ||
|
|
[address.first_name, address.last_name].filter(Boolean).join(' ');
|
|
|
|
return {
|
|
name: name || '',
|
|
email: customer?.email || '',
|
|
phone: address.phone || customer?.phone || '',
|
|
address1: address.line1 || address.address1 || '',
|
|
address2: address.line2 || address.address2 || '',
|
|
city: address.city || '',
|
|
state_code: address.state || address.state_code || '',
|
|
country_code: address.country || address.country_code || '',
|
|
zip: address.postal_code || address.zip || ''
|
|
};
|
|
}
|
|
|
|
buildItems(items) {
|
|
return items.map((item) => {
|
|
const syncVariantId =
|
|
item.sync_variant_id || item.printful_sync_variant_id;
|
|
const variantId = item.variant_id || item.printful_variant_id;
|
|
const quantity = item.quantity || item.qty || 1;
|
|
|
|
if (!syncVariantId && !variantId) {
|
|
throw new Error(
|
|
'Printful item missing sync_variant_id or variant_id.'
|
|
);
|
|
}
|
|
|
|
const payload = {
|
|
quantity,
|
|
...(syncVariantId ? { sync_variant_id: syncVariantId } : {}),
|
|
...(variantId ? { variant_id: variantId } : {})
|
|
};
|
|
|
|
if (item.retail_price) payload.retail_price = String(item.retail_price);
|
|
if (item.name) payload.name = item.name;
|
|
if (item.sku) payload.sku = item.sku;
|
|
if (item.files) payload.files = item.files;
|
|
|
|
return payload;
|
|
});
|
|
}
|
|
|
|
async createOrder({ external_id, items, customer, shipping }) {
|
|
const payload = {
|
|
external_id,
|
|
recipient: this.buildRecipient(customer, shipping),
|
|
items: this.buildItems(items)
|
|
};
|
|
|
|
if (!this.apiKey) {
|
|
return { simulated: true, payload };
|
|
}
|
|
|
|
const headers = {
|
|
Authorization: `Bearer ${this.apiKey}`,
|
|
'Content-Type': 'application/json'
|
|
};
|
|
if (this.storeId) headers['X-PF-Store-Id'] = this.storeId;
|
|
|
|
const resp = await axios.post(`${this.baseUrl}/orders`, payload, { headers });
|
|
return resp.data;
|
|
}
|
|
}
|
|
|
|
module.exports = PrintfulSupplier;
|