Raw
1 ---
2 products:
3 - fulfillment
4 - cart
5 - order
6 ---
7
8 import { Card, Prerequisites, Details } from "docs-ui"
9 import { Github } from "@medusajs/icons"
10
11 export const ogImage = "https://res.cloudinary.com/dza7lstvk/image/upload/v1734607836/Medusa%20Resources/integrations-shipstation_nlabgy.jpg"
12
13 export const metadata = {
14 title: `Integrate Medusa with ShipStation (Fulfillment)`,
15 openGraph: {
16 images: [
17 {
18 url: ogImage,
19 width: 1600,
20 height: 836,
21 type: "image/jpeg"
22 }
23 ],
24 },
25 twitter: {
26 images: [
27 {
28 url: ogImage,
29 width: 1600,
30 height: 836,
31 type: "image/jpeg"
32 }
33 ]
34 }
35 }
36
37 # {metadata.title}
38
39 In this guide, you'll learn how to integrate Medusa with ShipStation.
40
41 <Note title="Not a technical user?">
42
43 Refer your technical team to this guide to integrate ShipStation with your Medusa application. You can then enable it using the Medusa Admin as explained in [this user guide](!user-guide!/settings/locations-and-shipping/locations#manage-fulfillment-providers).
44
45 </Note>
46
47 When you install a Medusa application, you get a fully-fledged commerce platform with support for customizations. Medusa's [Fulfillment Module](../../../commerce-modules/fulfillment/page.mdx) provides fulfillment-related resources and functionalities in your store, but it delegates the processing and shipment of order fulfillments to providers that you can integrate.
48
49 [ShipStation](https://shipstation.com/) is a shipping toolbox that connects all your shipping providers within one platform. By integrating it with Medusa, you can allow customers to choose from different providers like DHL and FedEx and view price rates retrieved from ShipStation. Admin users will also process the order fulfillment using the ShipStation integration.
50
51 This guide will teach you how to:
52
53 - Install and set up Medusa.
54 - Set up a ShipStation account.
55 - Integrate ShipStation as a fulfillment provider in Medusa.
56
57 You can follow this guide whether you're new to Medusa or an advanced Medusa developer.
58
59 <Card
60 title="Example Repository"
61 text="Find the full code of the guide in this repository."
62 href="https://github.com/medusajs/examples/tree/main/shipstation-integration"
63 icon={Github}
64 />
65
66 ---
67
68 ## Step 1: Install a Medusa Application
69
70 <Prerequisites items={[
71 {
72 text: "Node.js v20.19.0+ or v22.12.0+",
73 link: "https://nodejs.org/en/download"
74 },
75 {
76 text: "Git CLI tool",
77 link: "https://git-scm.com/downloads"
78 },
79 {
80 text: "PostgreSQL",
81 link: "https://www.postgresql.org/download/"
82 }
83 ]} />
84
85 Start by installing the Medusa application on your machine with the following command:
86
87 ```bash
88 npx create-medusa-app@latest
89 ```
90
91 You'll first be asked for the project's name. Then, when you're asked whether you want to install the Next.js Starter Storefront, choose `Y` for yes.
92
93 Afterwards, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
94
95 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credential and submit the form.
96
97 Afterwards, you can login with the new user and explore the dashboard. The Next.js Starter Storefront is also running at `http://localhost:8000`.
98
99 <Note title="Ran into Errors?">
100
101 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
102
103 </Note>
104
105 <Note>
106
107 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
108
109 </Note>
110
111 ---
112
113 ## Step 2: Prepare ShipStation Account
114
115 In this step, you'll prepare your ShipStation account before integrating it into Medusa. If you don't have an account, create one [here](https://www.shipstation.com/start-a-free-trial).
116
117 ### Enable Carriers
118
119 To create labels for your shipments, you need to enable carriers. This requires you to enter payment and address details.
120
121 To enable carriers:
122
123 1. On the Onboard page, in the "Enable carriers & see rates" section, click on the "Enable Carriers" button.
124
125 ![Scroll down to the Enable carriers & see rates section, and find the "Enable Carriers" button.](https://res.cloudinary.com/dza7lstvk/image/upload/v1734523873/Medusa%20Resources/Screenshot_2024-12-18_at_2.10.54_PM_pmvcfr.png)
126
127 2. In the pop-up that opens, click on Continue Setup.
128
129 ![Click on the green Continue Setup button](https://res.cloudinary.com/dza7lstvk/image/upload/v1734524261/Medusa%20Resources/Screenshot_2024-12-18_at_2.11.47_PM_wsl98i.png)
130
131 3. In the next section of the form, you have to enter your payment details and billing address. Once done, click on Continue Setup.
132 4. After that, click the checkboxes on the Terms of Service section, then click the Finish Setup button.
133
134 ![Enable the two checkboxes, then click on Finish Setup at the bottom right](https://res.cloudinary.com/dza7lstvk/image/upload/v1734524486/Medusa%20Resources/Screenshot_2024-12-18_at_2.20.12_PM_pkixma.png)
135
136 5. Once you're done, you can optionally add funds to your account. If you're not US-based, make sure to disable ParcelGuard insurance. Otherwise, an error will occur while retrieving rates later.
137
138 ### Add Carriers
139
140 You must have at least one carrier (shipping provider) added in your ShipStation account. You'll later provide shipping options for each of these carriers in your Medusa application.
141
142 To add carriers:
143
144 1. On the Onboard page, in the "Enable carriers & see rates" section, click on the "Add your carrier accounts" link.
145
146 ![Scroll down to the Enable carriers & see rates section, and find the "Add your carrier accounts" link under the "Enable Carriers" button](https://res.cloudinary.com/dza7lstvk/image/upload/v1734336612/Medusa%20Resources/Screenshot_2024-12-16_at_10.09.08_AM_nqshhg.png)
147
148 2. Click on a provider from the pop-up window.
149
150 ![Click on the provider tiles in the pop-up window](https://res.cloudinary.com/dza7lstvk/image/upload/v1734336826/Medusa%20Resources/Screenshot_2024-12-16_at_10.13.37_AM_og4sdq.png)
151
152 Based on the provider you chose, you'll have to enter your account details, then submit the form.
153
154 ### Activate Shipping API
155
156 To integrate ShipStation using their API, you must enable the Shipping API Add-On. To do that:
157
158 1. Go to Add-Ons from the navigation bar.
159 2. Find Shipping API and activate it.
160
161 You'll later retrieve your API key.
162
163 ---
164
165 ## Step 3: Create ShipStation Module Provider
166
167 To integrate third-party services into Medusa, you create a custom module. A module is a re-usable package with functionalities related to a single feature or domain. Medusa integrates the module into your application without implications or side effects on your setup.
168
169 Medusa's Fulfillment Module delegates processing fulfillments and shipments to other modules, called module providers. In this step, you'll create a ShipStation Module Provider that implements all functionalities required for fulfillment. In later steps, you'll add into Medusa shipping options for ShipStation, and allow customers to choose it during checkout.
170
171 <Note>
172
173 Learn more about modules in [this documentation](!docs!/learn/fundamentals/modules).
174
175 </Note>
176
177 ### Create Module Directory
178
179 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/shipstation`.
180
181 ![The directory structure of the Medusa application after adding the module's directory](https://res.cloudinary.com/dza7lstvk/image/upload/v1734338950/Medusa%20Resources/shipstation-dir-overview-1_dlsrbv.jpg)
182
183 ### Create Service
184
185 You define a module's functionalities in a service. A service is a TypeScript or JavaScript class that the module exports. In the service's methods, you can connect to the database, which is useful if your module defines tables in the database, or connect to a third-party service.
186
187 In this section, you'll create the ShipStation Module Provider's service and the methods necessary to handle fulfillment.
188
189 Start by creating the file `src/modules/shipstation/service.ts` with the following content:
190
191 ![The directory structure of the Medusa application after adding the service](https://res.cloudinary.com/dza7lstvk/image/upload/v1734339042/Medusa%20Resources/shipstation-dir-overview-2_cmgvcj.jpg)
192
193 export const serviceHighlights1 = [
194 ["3", "ShipStationOptions", "The type of options that the module expects."],
195 ["7", "AbstractFulfillmentProviderService", "Fulfillment provider service must extend this class."],
196 ["8", "identifier", "Each fulfillment provider has a unique identifier."],
197 ["11", "options", "Receive the module's options as a second parameter."]
198 ]
199
200 ```ts title="src/modules/shipstation/service.ts" highlights={serviceHighlights1}
201 import { AbstractFulfillmentProviderService } from "@medusajs/framework/utils"
202
203 export type ShipStationOptions = {
204 api_key: string
205 }
206
207 class ShipStationProviderService extends AbstractFulfillmentProviderService {
208 static identifier = "shipstation"
209 protected options_: ShipStationOptions
210
211 constructor({}, options: ShipStationOptions) {
212 super()
213
214 this.options_ = options
215 }
216
217 // TODO add methods
218 }
219
220 export default ShipStationProviderService
221 ```
222
223 A Fulfillment Module Provider service must extend the `AbstractFulfillmentProviderService` class. You'll implement the abstract methods of this class in the upcoming sections.
224
225 The service must have an `identifier` static property, which is a unique identifier for the provider. You set the identifier to `shipstation`.
226
227 A module can receive options that are set when you later add the module to Medusa's configurations. These options allow you to safely store secret values outside of your code.
228
229 The ShipStation module requires an `api_key` option, indicating your ShipStation's API key. You receive the options as a second parameter of the service's constructor.
230
231 ### Create Client
232
233 To send requests to ShipStation, you'll create a client class that provides the methods to send requests. You'll then use that class in your service.
234
235 Create the file `src/modules/shipstation/client.ts` with the following content:
236
237 ![The directory structure of the Medusa application after adding the client file](https://res.cloudinary.com/dza7lstvk/image/upload/v1734339519/Medusa%20Resources/shipstation-dir-overview-3_b8im2d.jpg)
238
239 export const clientHighlights1 = [
240 ["5", "options", "Add the client options as a class property."],
241 ["11", "sendRequest", "Send a request to ShipStation."],
242 ["16", "api_key", "Pass the API key in the request header."],
243 ["19", "then", "Parse the response based on the content header."],
244 ["27", "then", "Throw possible errors in the response or return the response."]
245 ]
246
247 ```ts title="src/modules/shipstation/client.ts" highlights={clientHighlights1}
248 import { ShipStationOptions } from "./service"
249 import { MedusaError } from "@medusajs/framework/utils"
250
251 export class ShipStationClient {
252 options: ShipStationOptions
253
254 constructor(options) {
255 this.options = options
256 }
257
258 private async sendRequest(url: string, data?: RequestInit): Promise<any> {
259 return fetch(`https://api.shipstation.com/v2${url}`, {
260 ...data,
261 headers: {
262 ...data?.headers,
263 "api-key": this.options.api_key,
264 "Content-Type": "application/json",
265 },
266 }).then((resp) => {
267 const contentType = resp.headers.get("content-type")
268 if (!contentType?.includes("application/json")) {
269 return resp.text()
270 }
271
272 return resp.json()
273 })
274 .then((resp) => {
275 if (typeof resp !== "string" && resp.errors?.length) {
276 throw new MedusaError(
277 MedusaError.Types.INVALID_DATA,
278 `An error occurred while sending a request to ShipStation: ${
279 resp.errors.map((error) => error.message)
280 }`
281 )
282 }
283
284 return resp
285 })
286 }
287 }
288 ```
289
290 The `ShipStationClient` class accepts the ShipStation options in its constructor and sets those options in the `options` property.
291
292 You also add a private `sendRequest` method that accepts a path to send a request to and the request's configurations. In the method, you send a request using the Fetch API, passing the API key from the options in the request header. You also parse the response body based on its content type, and check if there are any errors to be thrown before returning the parsed response.
293
294 You'll add more methods to send requests in the upcoming steps.
295
296 To use the client in `ShipStationProviderService`, add it as a class property and initialize it in the constructor:
297
298 export const serviceHighlights2 = [
299 ["2", "", "Import the client."],
300 ["8", "client", "Add client property."],
301 ["12", "ShipStationClient", "Initialize the client."]
302 ]
303
304 ```ts title="src/modules/shipstation/service.ts" highlights={serviceHighlights2}
305 // imports...
306 import { ShipStationClient } from "./client"
307
308 // ...
309
310 class ShipStationProviderService extends AbstractFulfillmentProviderService {
311 // properties...
312 protected client: ShipStationClient
313
314 constructor({}, options: ShipStationOptions) {
315 // ...
316 this.client = new ShipStationClient(options)
317 }
318 }
319 ```
320
321 You import `ShipStationClient` and add a new `client` property in `ShipStationProviderService`. In the class's constructor, you set the `client` property by initializing `ShipStationProviderService`, passing it the module's options.
322
323 You'll use the `client` property when implementing the service's methods.
324
325 ### Implement Service Methods
326
327 In this section, you'll go back to the `ShipStationProviderService` method to implement the abstract methods of `AbstractFulfillmentProviderService`.
328
329 <Note>
330
331 Refer to [this guide](/references/fulfillment/provider) for a full reference of all methods, their parameters and return types.
332
333 </Note>
334
335 #### getFulfillmentOptions
336
337 The `getFulfillmentOptions` method returns the options that this fulfillment provider supports. When admin users add shipping options later in the Medusa Admin, they'll select one of these options.
338
339 <Note>
340
341 Learn more about shipping options in [this guide](../../../commerce-modules/fulfillment/shipping-option/page.mdx).
342
343 </Note>
344
345 ShipStation requires that a shipment must be associated with a carrier and one of its services. So, in this method, you'll retrieve the list of carriers from ShipStation and return them as fulfillment options. Shipping options created from these fulfillment options will always have access to the option's carrier and service.
346
347 Before you start implementing methods, you'll add the expected carrier types returned by ShipStation. Create the file `src/modules/shipstation/types.ts` with the following content:
348
349 ![The directory structure of the Medusa application after adding the types file](https://res.cloudinary.com/dza7lstvk/image/upload/v1734340402/Medusa%20Resources/shipstation-dir-overview-4_fwsle0.jpg)
350
351 ```ts title="src/modules/shipstation/types.ts"
352 export type Carrier = {
353 carrier_id: string
354 disabled_by_billing_plan: boolean
355 friendly_name: string
356 services: {
357 service_code: string
358 name: string
359 }[]
360 packages: {
361 package_code: string
362 }[]
363 [k: string]: unknown
364 }
365
366 export type CarriersResponse = {
367 carriers: Carrier[]
368 }
369 ```
370
371 You define a `Carrier` type that holds a carrier's details, and a `CarriersResponse` type, which is the response returned by ShipStation.
372
373 <Note title="Tip">
374
375 A carrier has more fields that you can use. Refer to [ShipStation's documentation](https://docs.shipstation.com/openapi/carriers/list_carriers#carriers/list_carriers/t=response&c=200&path=carriers) for all carrier fields.
376
377 </Note>
378
379 Next, you'll add in `ShipStationClient` the method to retrieve the carriers from ShipStation. So, add to the class defined in `src/modules/shipstation/client.ts` a new method:
380
381 export const clientHighlights2 = [
382 ["8", "getCarriers", "Add a method to get carriers from ShipStation."],
383 ["9", "sendRequest", "Use this method to send the request."]
384 ]
385
386 ```ts title="src/modules/shipstation/client.ts" highlights={clientHighlights2}
387 // other imports...
388 import {
389 CarriersResponse,
390 } from "./types"
391
392 export class ShipStationClient {
393 // ...
394 async getCarriers(): Promise<CarriersResponse> {
395 return await this.sendRequest("/carriers")
396 }
397 }
398 ```
399
400 You added a new `getCarriers` method that uses the `sendRequest` method to send a request to the [ShipStation's List Carriers endpoint](https://docs.shipstation.com/openapi/carriers/list_carriers). The method returns `CarriersResponse` that you defined earlier.
401
402 Finally, add the `getFulfillmentOptions` method to `ShipStationProviderService`:
403
404 export const serviceHighlights3 = [
405 ["8", "getFulfillmentOptions", "Method to return the options this fulfillment provider supports."],
406 ["9", "getCarriers", "Retrieve the carriers from ShipStation."],
407 ["13", "filter", "Filter out carriers that are disabled by the billing plan."],
408 ["15", "services", "Loop over the services that the carrier provides."],
409 ["16", "push", "Add an option for the carrier and service combination."]
410 ]
411
412 ```ts title="src/modules/shipstation/service.ts" highlights={serviceHighlights3}
413 // other imports...
414 import {
415 FulfillmentOption,
416 } from "@medusajs/framework/types"
417
418 class ShipStationProviderService extends AbstractFulfillmentProviderService {
419 // ...
420 async getFulfillmentOptions(): Promise<FulfillmentOption[]> {
421 const { carriers } = await this.client.getCarriers()
422 const fulfillmentOptions: FulfillmentOption[] = []
423
424 carriers
425 .filter((carrier) => !carrier.disabled_by_billing_plan)
426 .forEach((carrier) => {
427 carrier.services.forEach((service) => {
428 fulfillmentOptions.push({
429 id: `${carrier.carrier_id}__${service.service_code}`,
430 name: service.name,
431 carrier_id: carrier.carrier_id,
432 carrier_service_code: service.service_code,
433 })
434 })
435 })
436
437 return fulfillmentOptions
438 }
439 }
440 ```
441
442 In the `getFulfillmentOptions` method, you retrieve the carriers from ShipStation. You then filter out the carriers disabled by your ShipStation billing plan, and loop over the remaining carriers and their services.
443
444 You return an array of fulfillment-option objects, where each object represents a carrier and service pairing. Each object has the following properties:
445
446 - an `id` property, which you set to a combination of the carrier ID and the service code.
447 - a `name` property, which you set to the service's `name`. The admin user will see this name when they create a shipping option for the ShipStation provider.
448 - You can pass other data, such as `carrier_id` and `carrier_service_code`, and Medusa will store the fulfillment option in the `data` property of shipping options created later.
449
450 <Note>
451
452 Learn more about the shipping option's `data` property in [this guide](../../../commerce-modules/fulfillment/shipping-option/page.mdx).
453
454 </Note>
455
456 You'll see this method in action later when you create a shipping option.
457
458 #### canCalculate
459
460 When an admin user creates a shipping option for your provider, they can choose whether the price is flat rate or calculated during checkout.
461
462 If the user chooses calculated, Medusa validates that your fulfillment provider supports calculated prices using the `canCalculate` method of your provider's service.
463
464 This method accepts the shipping option's `data` field, which will hold the data of an option returned by `getFulfillmentOptions`. It returns a boolean value indicating whether the shipping option can have a calculated price.
465
466 Add the method to `ShipStationProviderService` in `src/modules/shipstation/service.ts`:
467
468 ```ts title="src/modules/shipstation/service.ts"
469 // other imports...
470 import {
471 // ...
472 CreateShippingOptionDTO,
473 } from "@medusajs/framework/types"
474
475 class ShipStationProviderService extends AbstractFulfillmentProviderService {
476 // ...
477 async canCalculate(data: CreateShippingOptionDTO): Promise<boolean> {
478 return true
479 }
480 }
481 ```
482
483 Since all shipping option prices can be calculated with ShipStation based on the chosen carrier and service zone, you always return `true` in this method.
484
485 You'll implement the calculation mechanism in a later method.
486
487 #### calculatePrice
488
489 When the customer views available shipping options during checkout, the Medusa application requests the calculated price from your fulfillment provider using its `calculatePrice` method.
490
491 To retrieve shipping prices with ShipStation, you create a shipment first then get its rates. So, in the `calculatePrice` method, you'll either:
492
493 - Send a request to [ShipStation's get shipping rates endpoint](https://docs.shipstation.com/openapi/rates/calculate_rates) that creates a shipment and returns its prices;
494 - Or, if a shipment was already created before, you'll retrieve its prices using [ShipStation's get shipment rates endpoint](https://docs.shipstation.com/openapi/shipments/list_shipment_rates).
495
496 First, add the following types to `src/modules/shipstation/types.ts`:
497
498 export const typesHighlights1 = [
499 ["1", "ShipStationAddress", "An address to ship from or to."],
500 ["21", "Rate", "A price rate for a specified carrier and service zone."],
501 ["45", "RateResponse", "The response when retrieving rates."],
502 ["49", "GetShippingRatesRequest", "The request body data for ShipStation's get shipping rates endpoint."],
503 ["59", "GetShippingRatesResponse", "The response of the ShipStation's get shipping rates endpoint."],
504 ["67", "Shipment", "A shipment's details."]
505 ]
506
507 ```ts title="src/modules/shipstation/types.ts" highlights={typesHighlights1}
508 export type ShipStationAddress = {
509 name: string
510 phone: string
511 email?: string | null
512 company_name?: string | null
513 address_line1: string
514 address_line2?: string | null
515 address_line3?: string | null
516 city_locality: string
517 state_province: string
518 postal_code: string
519 country_code: string
520 address_residential_indicator: "unknown" | "yes" | "no"
521 instructions?: string | null
522 geolocation?: {
523 type?: string
524 value?: string
525 }[]
526 }
527
528 export type Rate = {
529 rate_id: string
530 shipping_amount: {
531 currency: string
532 amount: number
533 }
534 insurance_amount: {
535 currency: string
536 amount: number
537 }
538 confirmation_amount: {
539 currency: string
540 amount: number
541 }
542 other_amount: {
543 currency: string
544 amount: number
545 }
546 tax_amount: {
547 currency: string
548 amount: number
549 }
550 }
551
552 export type RateResponse = {
553 rates: Rate[]
554 }
555
556 export type GetShippingRatesRequest = {
557 shipment_id?: string
558 shipment?: Omit<Shipment, "shipment_id" | "shipment_status">
559 rate_options: {
560 carrier_ids: string[]
561 service_codes: string[]
562 preferred_currency: string
563 }
564 }
565
566 export type GetShippingRatesResponse = {
567 shipment_id: string
568 carrier_id?: string
569 service_code?: string
570 external_order_id?: string
571 rate_response: RateResponse
572 }
573
574 export type Shipment = {
575 shipment_id: string
576 carrier_id: string
577 service_code: string
578 ship_to: ShipStationAddress
579 return_to?: ShipStationAddress
580 is_return?: boolean
581 ship_from: ShipStationAddress
582 items?: [
583 {
584 name?: string
585 quantity?: number
586 sku?: string
587 }
588 ]
589 warehouse_id?: string
590 shipment_status: "pending" | "processing" | "label_purchased" | "cancelled"
591 [k: string]: unknown
592 }
593
594 ```
595
596 You add the following types:
597
598 - `ShipStationAddress`: an address to ship from or to.
599 - `Rate`: a price rate for a specified carrier and service zone.
600 - `RateResponse`: The response when retrieving rates.
601 - `GetShippingRatesRequest`: The request body data for [ShipStation's get shipping rates endpoint](https://docs.shipstation.com/openapi/rates/calculate_rates). You can refer to their API reference for other accepted parameters.
602 - `GetShippingRatesResponse`: The response of the [ShipStation's get shipping rates endpoint](https://docs.shipstation.com/openapi/rates/calculate_rates). You can refer to their API reference for other response fields.
603 - `Shipment`: A shipment's details.
604
605 Then, add the following methods to `ShipStationClient`:
606
607 export const serviceHighlights7 = [
608 ["11", "getShippingRates", "Create a shipment and retrieve its rates."],
609 ["31", "getShipmentRates", "Get the rates of a shipment."]
610 ]
611
612 ```ts title="src/modules/shipstation/client.ts" highlights={serviceHighlights7}
613 // other imports...
614 import {
615 // ...
616 GetShippingRatesRequest,
617 GetShippingRatesResponse,
618 RateResponse,
619 } from "./types"
620
621 export class ShipStationClient {
622 // ...
623 async getShippingRates(
624 data: GetShippingRatesRequest
625 ): Promise<GetShippingRatesResponse> {
626 return await this.sendRequest("/rates", {
627 method: "POST",
628 body: JSON.stringify(data),
629 }).then((resp) => {
630 if (resp.rate_response.errors?.length) {
631 throw new MedusaError(
632 MedusaError.Types.INVALID_DATA,
633 `An error occurred while retrieving rates from ShipStation: ${
634 resp.rate_response.errors.map((error) => error.message)
635 }`
636 )
637 }
638
639 return resp
640 })
641 }
642
643 async getShipmentRates(id: string): Promise<RateResponse[]> {
644 return await this.sendRequest(`/shipments/${id}/rates`)
645 }
646 }
647 ```
648
649 The `getShippingRates` method accepts as a parameter the data to create a shipment and retrieve its rate. In the method, you send the request using the `sendRequest` method, and throw any errors in the rate retrieval before returning the response.
650
651 The `getShipmentRates` method accepts the ID of the shipment as a parameter, sends the request using the `sendRequest` method and returns its response holding the shipment's rates.
652
653 Next, add to `ShipStationProviderService` a private method that'll be used to create a shipment in ShipStation and get its rates:
654
655 export const serviceHighlights8 = [
656 ["17", "createShipment", "Add method to create a shipment and get its rate."],
657 ["45", "ship_from", "Prepare the address to ship items from."],
658 ["62", "ship_to", "Prepare the address to ship items to."]
659 ]
660
661 ```ts title="src/modules/shipstation/service.ts" highlights={serviceHighlights8}
662 // other imports...
663 import {
664 // ...
665 MedusaError,
666 } from "@medusajs/framework/utils"
667 import {
668 // ...
669 CalculateShippingOptionPriceDTO,
670 } from "@medusajs/framework/types"
671 import {
672 GetShippingRatesResponse,
673 ShipStationAddress,
674 } from "./types"
675
676 class ShipStationProviderService extends AbstractFulfillmentProviderService {
677 // ...
678 private async createShipment({
679 carrier_id,
680 carrier_service_code,
681 from_address,
682 to_address,
683 items,
684 currency_code,
685 }: {
686 carrier_id: string
687 carrier_service_code: string
688 from_address?: {
689 name?: string
690 address?: Omit<
691 StockLocationAddressDTO, "created_at" | "updated_at" | "deleted_at"
692 >
693 },
694 to_address?: Omit<
695 CartAddressDTO, "created_at" | "updated_at" | "deleted_at" | "id"
696 >,
697 items: CartLineItemDTO[] | OrderLineItemDTO[],
698 currency_code: string
699 }): Promise<GetShippingRatesResponse> {
700 if (!from_address?.address) {
701 throw new MedusaError(
702 MedusaError.Types.INVALID_DATA,
703 "from_location.address is required to calculate shipping rate"
704 )
705 }
706 const ship_from: ShipStationAddress = {
707 name: from_address?.name || "",
708 phone: from_address?.address?.phone || "",
709 address_line1: from_address?.address?.address_1 || "",
710 city_locality: from_address?.address?.city || "",
711 state_province: from_address?.address?.province || "",
712 postal_code: from_address?.address?.postal_code || "",
713 country_code: from_address?.address?.country_code || "",
714 address_residential_indicator: "unknown",
715 }
716 if (!to_address) {
717 throw new MedusaError(
718 MedusaError.Types.INVALID_DATA,
719 "shipping_address is required to calculate shipping rate"
720 )
721 }
722
723 const ship_to: ShipStationAddress = {
724 name: `${to_address.first_name} ${to_address.last_name}`,
725 phone: to_address.phone || "",
726 address_line1: to_address.address_1 || "",
727 city_locality: to_address.city || "",
728 state_province: to_address.province || "",
729 postal_code: to_address.postal_code || "",
730 country_code: to_address.country_code || "",
731 address_residential_indicator: "unknown",
732 }
733
734 // TODO create shipment
735 }
736 }
737 ```
738
739 The `createShipment` method accepts as a parameter an object having the following properties:
740
741 - `carrier_id`: The ID of the carrier to create the shipment for.
742 - `carrier_service_code`: The code of the carrier's service.
743 - `from_address`: The address to ship items from, which is the address of the stock location associated with a shipping option.
744 - `to_address`: The address to ship items to, which is the customer's address.
745 - `items`: An array of the items in the cart or order (for fulfilling the order later).
746 - `currency_code`: The currency code of the cart or order.
747
748 In the `createShipment` method, so far you only prepare the data to be sent to ShipStation. ShipStation requires the addresses to ship the items from and to.
749
750 To send the request, replace the `TODO` with the following:
751
752 ```ts title="src/modules/shipstation/service.ts"
753 // Sum the package's weight
754 // You can instead create different packages for each item
755 const packageWeight = items.reduce((sum, item) => {
756 // @ts-ignore
757 return sum + (item.variant.weight || 0)
758 }, 0)
759
760 return await this.client.getShippingRates({
761 shipment: {
762 carrier_id: carrier_id,
763 service_code: carrier_service_code,
764 ship_to,
765 ship_from,
766 validate_address: "no_validation",
767 items: items?.map((item) => ({
768 name: item.title,
769 quantity: item.quantity,
770 sku: item.variant_sku || "",
771 })),
772 packages: [{
773 weight: {
774 value: packageWeight,
775 unit: "kilogram",
776 },
777 }],
778 customs: {
779 contents: "merchandise",
780 non_delivery: "return_to_sender",
781 },
782 },
783 rate_options: {
784 carrier_ids: [carrier_id],
785 service_codes: [carrier_service_code],
786 preferred_currency: currency_code as string,
787 },
788 })
789 ```
790
791 You create a shipment and get its rates using the `getShippingRates` method you added to the client. You pass the method the expected request body parameters by [ShipStation's get shipping rates endpoint](https://docs.shipstation.com/openapi/rates/calculate_rates), including the carrier ID, the items to be shipped, and more.
792
793 <Note title="Tip">
794
795 The above snippet assumes all items are sent in a single package. You can instead pass a package for each item, specifying its weight and optionally its height, width, and length.
796
797 </Note>
798
799 Finally, add the `calculatePrice` method to `ShipStationProviderService`:
800
801 export const serviceHighlights5 = [
802 ["14", "shipment_id", "Retrieve the shipping method's shipment ID."],
803 ["24", "createShipment", "If a shipment isn't already created, create the shipment and get its rates."],
804 ["37", "getShipmentRates", "If a shipment is already created, retrieve its rates."],
805 ["41", "calculatedPrice", "Calculate the price from the specified rate."],
806 ["47", "is_calculated_price_tax_inclusive", "Return whether the price includes taxes."]
807 ]
808
809 ```ts title="src/modules/shipstation/service.ts" highlights={serviceHighlights5}
810 // other imports...
811 import {
812 // ...
813 CalculatedShippingOptionPrice,
814 } from "@medusajs/framework/types"
815
816 class ShipStationProviderService extends AbstractFulfillmentProviderService {
817 // ...
818 async calculatePrice(
819 optionData: CalculateShippingOptionPriceDTO["optionData"],
820 data: CalculateShippingOptionPriceDTO["data"],
821 context: CalculateShippingOptionPriceDTO["context"]
822 ): Promise<CalculatedShippingOptionPrice> {
823 const { shipment_id } = data as {
824 shipment_id?: string
825 } || {}
826 const { carrier_id, carrier_service_code } = optionData as {
827 carrier_id: string
828 carrier_service_code: string
829 }
830 let rate: Rate | undefined
831
832 if (!shipment_id) {
833 const shipment = await this.createShipment({
834 carrier_id,
835 carrier_service_code,
836 from_address: {
837 name: context.from_location?.name,
838 address: context.from_location?.address,
839 },
840 to_address: context.shipping_address,
841 items: context.items || [],
842 currency_code: context.currency_code as string,
843 })
844 rate = shipment.rate_response.rates[0]
845 } else {
846 const rateResponse = await this.client.getShipmentRates(shipment_id)
847 rate = rateResponse[0].rates[0]
848 }
849
850 const calculatedPrice = !rate ? 0 : rate.shipping_amount.amount + rate.insurance_amount.amount +
851 rate.confirmation_amount.amount + rate.other_amount.amount +
852 (rate.tax_amount?.amount || 0)
853
854 return {
855 calculated_amount: calculatedPrice,
856 is_calculated_price_tax_inclusive: !!rate?.tax_amount,
857 }
858 }
859 }
860 ```
861
862 The `calculatePrice` method accepts the following parameters:
863
864 1. The `data` property of the chosen shipping option during checkout.
865 2. The `data` property of the shipping method, which will hold the ID of the shipment in ShipStation.
866 3. An object of the checkout's context, including the cart's items, the location associated with the shipping option, and more.
867
868 In the method, you first check if a `shipment_id` is already stored in the shipping method's `data` property. If so, you retrieve the shipment's rates using the client's `getShipmentRates` method. Otherwise, you use the `createShipment` method to create the shipment and get its rates.
869
870 A rate returned by ShipStation has four properties that, when added up, make up the full price: `shipping_amount`, `insurance_amount`, `confirmation_amount`, and `other_amount`. It may have a `tax_amount` property, which is the amount for applied taxes.
871
872 <Note>
873
874 Learn more about these fields in [ShipStation's documentation](https://docs.shipstation.com/rate-shopping#about-the-response).
875
876 </Note>
877
878 The method returns an object having the following properties:
879
880 - `calculated_amount`: The shipping method's price calculated by adding the four rate properties with the tax property, if available.
881 - `is_calculated_price_tax_inclusive`: Whether the price includes taxes, which is inferred from whether the `tax_amount` property is set in the rate.
882
883 Customers will now see the calculated price of a ShipStation shipping option during checkout.
884
885 #### validateFulfillmentData
886
887 When a customer chooses a shipping option during checkout, Medusa creates a shipping method from that option. A shipping method has a `data` property to store data relevant for later processing of the method and its fulfillments.
888
889 So, in the `validateFulfillmentData` method of your provider, you'll create a shipment in ShipStation if it wasn't already created using their [get shipping rates endpoint](https://docs.shipstation.com/openapi/rates/calculate_rates), and store the ID of that shipment in the created shipping method's `data` property.
890
891 Add the `validateFulfillmentData` method to `ShipStationProviderService`:
892
893 export const serviceHighlights4 = [
894 ["8", "shipment_id", "Get the ID of an already created shipment, if available."],
895 ["17", "createShipment", "Create a shipment if it doesn't already exist."],
896 ["38", "shipment_id", "Store the shipment ID in the shipping method's `data`."]
897 ]
898
899 ```ts title="src/modules/shipstation/service.ts" highlights={serviceHighlights4}
900 class ShipStationProviderService extends AbstractFulfillmentProviderService {
901 // ...
902 async validateFulfillmentData(
903 optionData: Record<string, unknown>,
904 data: Record<string, unknown>,
905 context: Record<string, unknown>
906 ): Promise<any> {
907 let { shipment_id } = data as {
908 shipment_id?: string
909 }
910
911 if (!shipment_id) {
912 const { carrier_id, carrier_service_code } = optionData as {
913 carrier_id: string
914 carrier_service_code: string
915 }
916 const shipment = await this.createShipment({
917 carrier_id,
918 carrier_service_code,
919 from_address: {
920 // @ts-ignore
921 name: context.from_location?.name,
922 // @ts-ignore
923 address: context.from_location?.address,
924 },
925 // @ts-ignore
926 to_address: context.shipping_address,
927 // @ts-ignore
928 items: context.items || [],
929 // @ts-ignore
930 currency_code: context.currency_code,
931 })
932 shipment_id = shipment.shipment_id
933 }
934
935 return {
936 ...data,
937 shipment_id,
938 }
939 }
940 }
941 ```
942
943 The `validateFulfillmentData` method accepts the following parameters:
944
945 1. The `data` property of the chosen shipping option during checkout. It will hold the carrier ID and its service code.
946 2. The `data` property of the shipping method to be created. This can hold custom data sent in the [Add Shipping Method API route](!api!/store/carts/add-shipping-method).
947 3. An object of the checkout's context, including the cart's items, the location associated with the shipping option, and more.
948
949 In the method, you try to retrieve the shipment ID from the shipping method's `data` parameter if it was already created. If not, you create the shipment in ShipStation using the `createShipment` method.
950
951 Finally, you return the object to be stored in the shipping method's `data` property. You include in it the ID of the shipment in ShipStation.
952
953 #### createFulfillment
954
955 After the customer places the order, the admin user can manage its fulfillments. When the admin user creates a fulfillment for the order, Medusa uses the `createFulfillment` method of the associated provider to handle any processing in the third-party provider.
956
957 This method supports creating split fulfillments, meaning you can partially fulfill and order's items. So, you'll create a new shipment, then purchase a label for that shipment. You'll use the existing shipment to retrieve details like the address to ship from and to.
958
959 First, add a new type to `src/modules/shipstation/types.ts`:
960
961 ```ts title="src/modules/shipstation/types.ts"
962 export type Label = {
963 label_id: string
964 status: "processing" | "completed" | "error" | "voided"
965 shipment_id: string
966 ship_date: Date
967 shipment_cost: {
968 currency: string
969 amount: number
970 }
971 insurance_cost: {
972 currency: string
973 amount: number
974 }
975 confirmation_amount: {
976 currency: string
977 amount: number
978 }
979 tracking_number: string
980 is_return_label: boolean
981 carrier_id: string
982 service_code: string
983 trackable: string
984 tracking_status: "unknown" | "in_transit" | "error" | "delivered"
985 label_download: {
986 href: string
987 pdf: string
988 png: string
989 zpl: string
990 }
991 }
992 ```
993
994 You add the `Label` type for the details in a label object. You can find more properties in [ShipStation's documentation](https://docs.shipstation.com/openapi/labels/create_label#labels/create_label/response&c=200/body).
995
996 Then, add the following methods to the `ShipStationClient`:
997
998 ```ts title="src/modules/shipstation/client.ts"
999 // other imports...
1000 import {
1001 // ...
1002 Label,
1003 Shipment,
1004 } from "./types"
1005
1006 export class ShipStationClient {
1007 // ...
1008
1009 async getShipment(id: string): Promise<Shipment> {
1010 return await this.sendRequest(`/shipments/${id}`)
1011 }
1012
1013 async purchaseLabelForShipment(id: string): Promise<Label> {
1014 return await this.sendRequest(`/labels/shipment/${id}`, {
1015 method: "POST",
1016 body: JSON.stringify({}),
1017 })
1018 }
1019 }
1020 ```
1021
1022 You add the `getShipment` method to retrieve a shipment's details, and the `purchaseLabelForShipment` method to purchase a label in ShipStation for a shipment by its ID.
1023
1024 Finally, add the `createFulfillment` method in `ShipStationProviderService`:
1025
1026 export const serviceHighlights6 = [
1027 ["9", "shipment_id", "Retrieve the shipping method's shipment ID."],
1028 ["13", "originalShipment", "Retrieve the original shipment associated with the order's shipping method."],
1029 ["15", "orderItemsToFulfill", "Get the order items to fulfill."],
1030 ["29", "quantity", "Set the quantity based on the quantity to be fulfilled."],
1031 ["33", "newShipment", "Create a new shipment for the fulfillment."],
1032 ["56", "label", "Purchase a label for the new shipment."],
1033 ["59", "data", "Store the ID of the label and its shipment in the fulfillment's data property."]
1034 ]
1035
1036 ```ts title="src/modules/shipstation/service.ts" highlights={serviceHighlights6}
1037 class ShipStationProviderService extends AbstractFulfillmentProviderService {
1038 // ...
1039 async createFulfillment(
1040 data: object,
1041 items: object[],
1042 order: object | undefined,
1043 fulfillment: Record<string, unknown>
1044 ): Promise<any> {
1045 const { shipment_id } = data as {
1046 shipment_id: string
1047 }
1048
1049 const originalShipment = await this.client.getShipment(shipment_id)
1050
1051 const orderItemsToFulfill = []
1052
1053 items.map((item) => {
1054 // @ts-ignore
1055 const orderItem = order.items.find((i) => i.id === item.line_item_id)
1056
1057 if (!orderItem) {
1058 return
1059 }
1060
1061 // @ts-ignore
1062 orderItemsToFulfill.push({
1063 ...orderItem,
1064 // @ts-ignore
1065 quantity: item.quantity,
1066 })
1067 })
1068
1069 const newShipment = await this.createShipment({
1070 carrier_id: originalShipment.carrier_id,
1071 carrier_service_code: originalShipment.service_code,
1072 from_address: {
1073 name: originalShipment.ship_from.name,
1074 address: {
1075 ...originalShipment.ship_from,
1076 address_1: originalShipment.ship_from.address_line1,
1077 city: originalShipment.ship_from.city_locality,
1078 province: originalShipment.ship_from.state_province,
1079 },
1080 },
1081 to_address: {
1082 ...originalShipment.ship_to,
1083 address_1: originalShipment.ship_to.address_line1,
1084 city: originalShipment.ship_to.city_locality,
1085 province: originalShipment.ship_to.state_province,
1086 },
1087 items: orderItemsToFulfill as OrderLineItemDTO[],
1088 // @ts-ignore
1089 currency_code: order.currency_code,
1090 })
1091
1092 const label = await this.client.purchaseLabelForShipment(newShipment.shipment_id)
1093
1094 return {
1095 data: {
1096 ...(fulfillment.data as object || {}),
1097 label_id: label.label_id,
1098 shipment_id: label.shipment_id,
1099 },
1100 }
1101 }
1102 }
1103 ```
1104
1105 This method accepts the following parameters:
1106
1107 - `data`: The `data` property of the associated shipping method, which holds the ID of the shipment.
1108 - `items`: The items to fulfill.
1109 - `order`: The order's details.
1110 - `fulfillment`: The details of the fulfillment to be created.
1111
1112 In the method, you:
1113
1114 - Retrieve the details of the shipment originally associated with the fulfillment's shipping method.
1115 - Filter out the order items to retrieve the items to fulfill.
1116 - Create a new shipment for the items to fulfill. You use the original shipment for details like the carrier ID or the addresses to ship from and to.
1117 - Purchase a label for the new shipment.
1118
1119 You return an object whose `data` property will be stored in the created fulfillment's `data` property. You store in it the ID of the purchased label and the ID of its associated shipment.
1120
1121 #### cancelFulfillment
1122
1123 The last method you'll implement is the `cancelFulfillment` method. When an admin user cancels a fulfillment, Medusa uses the associated provider's `cancelFulfillment` method to perform any necessary actions in the third-party provider.
1124
1125 You'll use this method to void the label in ShipStation that was purchased in the `createFulfillment` method and cancel its associated shipment.
1126
1127 Start by adding the following type to `src/modules/shipstation/types.ts`:
1128
1129 ```ts title="src/modules/shipstation/types.ts"
1130 export type VoidLabelResponse = {
1131 approved: boolean
1132 message: string
1133 reason_code?: string
1134 }
1135 ```
1136
1137 `VoidLabelResponse` is the response type of [ShipStation's void label endpoint](https://docs.shipstation.com/openapi/labels/void_label).
1138
1139 Next, add two methods to `ShipStationClient`:
1140
1141 export const clientHighlights4 = [
1142 ["9", "voidLabel", "Void a label in ShipStation."],
1143 ["15", "cancelShipment", "Cancel a shipment in ShipStation."]
1144 ]
1145
1146 ```ts title="src/modules/shipstation/client.ts" highlights={clientHighlights4}
1147 // other imports...
1148 import {
1149 // ...
1150 VoidLabelResponse,
1151 } from "./types"
1152
1153 export class ShipStationClient {
1154 // ...
1155 async voidLabel(id: string): Promise<VoidLabelResponse> {
1156 return await this.sendRequest(`/labels/${id}/void`, {
1157 method: "PUT",
1158 })
1159 }
1160
1161 async cancelShipment(id: string): Promise<void> {
1162 return await this.sendRequest(`/shipments/${id}/cancel`, {
1163 method: "PUT",
1164 })
1165 }
1166 }
1167 ```
1168
1169 You added two methods:
1170
1171 - `voidLabel` that accepts the ID of a label to void using [ShipStation's endpoint](https://docs.shipstation.com/openapi/labels/void_label).
1172 - `cancelShipment` that accepts the ID of a shipment to cancel using [ShipStation's endpoint](https://docs.shipstation.com/openapi/shipments/cancel_shipments).
1173
1174 Finally, in `ShipStationProviderService`, add the `cancelFulfillment` method:
1175
1176 ```ts title="src/modules/shipstation/service.ts"
1177 class ShipStationProviderService extends AbstractFulfillmentProviderService {
1178 // ...
1179 async cancelFulfillment(data: Record<string, unknown>): Promise<any> {
1180 const { label_id, shipment_id } = data as {
1181 label_id: string
1182 shipment_id: string
1183 }
1184
1185 await this.client.voidLabel(label_id)
1186 await this.client.cancelShipment(shipment_id)
1187 }
1188 }
1189 ```
1190
1191 This method accepts the fulfillment's `data` property as a parameter. You get the ID of the label and shipment from the `data` parameter.
1192
1193 Then, you use the client's `voidLabel` method to void the label, and `cancelShipment` to cancel the shipment.
1194
1195 <Note>
1196
1197 Refer to [this guide](/references/fulfillment/provider) for a full reference of all methods, their parameters and return types.
1198
1199 </Note>
1200
1201 ### Export Module Definition
1202
1203 The `ShipStationProviderService` class now has the methods necessary to handle fulfillments.
1204
1205 Next, you must export the module provider's definition, which lets Medusa know what module this provider belongs to and its service.
1206
1207 Create the file `src/modules/shipstation/index.ts` with the following content:
1208
1209 ![The directory structure of the Medusa application after adding the index file](https://res.cloudinary.com/dza7lstvk/image/upload/v1734350125/Medusa%20Resources/shipstation-dir-overview-5_zs6beg.jpg)
1210
1211 ```ts title="src/modules/shipstation/index.ts"
1212 import ShipStationProviderService from "./service"
1213 import {
1214 ModuleProvider,
1215 Modules,
1216 } from "@medusajs/framework/utils"
1217
1218 export default ModuleProvider(Modules.FULFILLMENT, {
1219 services: [ShipStationProviderService],
1220 })
1221 ```
1222
1223 You export the module provider's definition using `ModuleProvider` from the Modules SDK. It accepts as a first parameter the name of the module that this provider belongs to, which is the Fulfillment Module. It also accepts as a second parameter an object having a `service` property indicating the provider's service.
1224
1225 ### Add Module to Configurations
1226
1227 Finally, to register modules and module providers in Medusa, you must add them to Medusa's configurations.
1228
1229 Medusa's configurations are set in the `medusa-config.ts` file, which is at the root directory of your Medusa application. The configuration object accepts a `modules` array, whose value is an array of modules to add to the application.
1230
1231 Add the `modules` property to the exported configurations in `medusa-config.ts`:
1232
1233 ```ts title="medusa-config.ts"
1234 module.exports = defineConfig({
1235 // ...
1236 modules: [
1237 {
1238 resolve: "@medusajs/medusa/fulfillment",
1239 options: {
1240 providers: [
1241 // default provider
1242 {
1243 resolve: "@medusajs/medusa/fulfillment-manual",
1244 id: "manual",
1245 },
1246 {
1247 resolve: "./src/modules/shipstation",
1248 id: "shipstation",
1249 options: {
1250 api_key: process.env.SHIPSTATION_API_KEY,
1251 },
1252 },
1253 ],
1254 },
1255 },
1256 ],
1257 })
1258 ```
1259
1260 In the `modules` array, you pass a module object having the following properties:
1261
1262 - `resolve`: The NPM package of the Fulfillment Module. Since the ShipStation Module is a Fulfillment Module Provider, it'll be passed in the options of the Fulfillment Module.
1263 - `options`: An object of options to pass to the module. It has a `providers` property which is an array of module providers to register. Each module provider object has the following properties:
1264 - `resolve`: The path to the module provider to register in the application. It can also be the name of an NPM package.
1265 - `id`: A unique ID, which Medusa will use along with the `identifier` static property that you set earlier in the class to identify this module provider.
1266 - `options`: An object of options to pass to the module provider. These are the options you expect and use in the module provider's service.
1267
1268 The values of the ShipStation Module's options are set in environment variables. So, add the following environment variables to `.env`:
1269
1270 ```shell
1271 SHIPSTATION_API_KEY=123...
1272 ```
1273
1274 Where `SHIPSTATION_API_KEY` is the ShipStation API key, which you can retrieve on the ShipStation dashboard:
1275
1276 - Click on the cog icon in the navigation bar to go to Settings.
1277
1278 ![The cog icon is at the top right of the navigation bar. It's the third icon from the right.](https://res.cloudinary.com/dza7lstvk/image/upload/v1734352047/Medusa%20Resources/Screenshot_2024-12-16_at_2.27.02_PM_nnmwzo.png)
1279
1280 - In the sidebar, expand Account and click on API Settings
1281
1282 ![The sidebar has an Account expandable. When you click on it, more items will show. Click on the API Settings](https://res.cloudinary.com/dza7lstvk/image/upload/v1734352145/Medusa%20Resources/Screenshot_2024-12-16_at_2.28.32_PM_wwfc1s.png).
1283
1284 - On the API Settings page, make sure V2 API is selected for "Select API Version" field, then click the "Generate API Key" button.
1285
1286 ![Make sure V2 API is selected in the Select API Version dropdown, then click on the "Generate API Key" button.](https://res.cloudinary.com/dza7lstvk/image/upload/v1734352261/Medusa%20Resources/Screenshot_2024-12-16_at_2.30.31_PM_vbkz4i.png)
1287
1288 - Copy the generated API key and use it as the value of the `SHIPSTATION_API_KEY` environment variable.
1289
1290 ---
1291
1292 ## Step 4: Add Shipping Options for ShipStation
1293
1294 Now that you've integrated ShipStation, you need to create its shipping options so that customers can choose from them during checkout.
1295
1296 First, start the Medusa application:
1297
1298 ```bash npm2yarn
1299 npm run dev
1300 ```
1301
1302 Then:
1303
1304 1. Open the Medusa Admin at `http://localhost:9000/app` and log in.
1305 2. Go to Settings -> Locations & Shipping
1306
1307 ![After clicking on settings in the main dashboard, a new sidebar will be shown where you can click on Location & Shipping](https://res.cloudinary.com/dza7lstvk/image/upload/v1733923761/Medusa%20Resources/Screenshot_2024-12-11_at_2.41.25_PM_wjbq5f.png)
1308
1309 3. Each location has shipping options. So, either create a new location, or click on the "View details" link at the top-right of a location.
1310
1311 ![A location's card has the "View details" link at the top-right.](https://res.cloudinary.com/dza7lstvk/image/upload/v1733923793/Medusa%20Resources/Screenshot_2024-12-11_at_2.41.50_PM_idglsu.png)
1312
1313 4. On the location's page and under the Fulfillment Providers section, click on the three-dots icon and choose Edit from the dropdown.
1314
1315 ![The location's page has as a "Fulfillment Providers" section in the side column at the right. Click on the three-dots icon in that section and choose Edit from the dropdown](https://res.cloudinary.com/dza7lstvk/image/upload/v1733923832/Medusa%20Resources/Screenshot_2024-12-11_at_2.42.47_PM_rzbjbf.png)
1316
1317 5. A pop up will open with the list of all integrated fulfillment providers. Click the checkbox at the left of the "Shipstation" provider, then click Save.
1318
1319 ![Choose the fulfillment provider from the list and click on the Save button](https://res.cloudinary.com/dza7lstvk/image/upload/v1734517015/Medusa%20Resources/Screenshot_2024-12-18_at_12.06.05_PM_nkmljy.png)
1320
1321 6. Under the Shipping section, click on the "Create option" link.
1322
1323 ![The Create Option link is in the Shipping section next to shipping options](https://res.cloudinary.com/dza7lstvk/image/upload/v1734517185/Medusa%20Resources/Screenshot_2024-12-18_at_12.19.26_PM_o3yz4n.png)
1324
1325 7. In the form that opens:
1326 - Select Calculated for the price type.
1327 - Enter a name for the shipping option. This is the name that customers see in the storefront.
1328 - Choose a Shipping Profile.
1329 - Choose ShipStation for Fulfillment Provider
1330 - This will load in the "Fulfillment option" field the ShipStation provider's options, which are retrieved on the server from the provider's `getFulfillmentOptions` method. Once they're loaded, choose one of the options retrieved from ShipStation.
1331 - Click the Save button.
1332
1333 ![Select Calculated for price type, and select the correct fulfillment provider and option](https://res.cloudinary.com/dza7lstvk/image/upload/v1734517536/Medusa%20Resources/Screenshot_2024-12-18_at_12.24.44_PM_yk7s3z.png)
1334
1335 You can create a shipping option for each fulfillment option.
1336
1337 Customers can now select this shipping option during checkout, and the fulfillment for their order will be processed by ShipStation.
1338
1339 ---
1340
1341 ## Test it Out: Place an Order and Fulfill It
1342
1343 To test out the integration, you'll place an order using the Next.js Starter Storefront you installed with the Medusa application. You'll then create a fulfillment for the order's items from the Medusa Admin dashboard.
1344
1345 ### Place Order in Storefront
1346
1347 Open the terminal in the Next.js Starter Storefront's directory (`apps/storefront`).
1348
1349 Then, while the Medusa application is running, run the following command in the storefront's directory:
1350
1351 ```bash npm2yarn
1352 npm run dev
1353 ```
1354
1355 This will run the storefront at `http://localhost:8000`. Open it in your browser, then:
1356
1357 1. Click on Menu at the top left of the navigation bar, then choose Store.
1358
1359 ![After you click on Menu, choose Store from the side menu.](https://res.cloudinary.com/dza7lstvk/image/upload/v1734518126/Medusa%20Resources/Screenshot_2024-12-18_at_12.35.10_PM_knk46m.png)
1360
1361 2. Click on a product and add it to the cart.
1362
1363 ![On a product's page, choose and option then click "add to cart"](https://res.cloudinary.com/dza7lstvk/image/upload/v1734518298/Medusa%20Resources/Screenshot_2024-12-18_at_12.36.18_PM_lrqnsj.png)
1364
1365 3. Click on "Cart" at the top right to go to the cart's page.
1366
1367 ![Click on Cart at the top right of the navigation bar.](https://res.cloudinary.com/dza7lstvk/image/upload/v1734518298/Medusa%20Resources/Screenshot_2024-12-18_at_12.36.59_PM_hmvpgb.png)
1368
1369 4. From the cart's page, click on "Go to checkout".
1370
1371 ![The "Go to checkout" button is at the bottom right of the page.](https://res.cloudinary.com/dza7lstvk/image/upload/v1734518298/Medusa%20Resources/Screenshot_2024-12-18_at_12.37.52_PM_ma4dij.png)
1372
1373 5. Enter the customer address as a first step of the Checkout. Make sure that the country you choose is the same as the location that the fulfillment provider's options are available in.
1374
1375 <Note>
1376
1377 If you're entering US-based address, make sure to enter the two-letter code for your state, as that's required by ShipStation.
1378
1379 </Note>
1380
1381 6. In the Delivery step, you'll find the option you added for ShipStation. There will be a loading indicator while its price is fetched, and the price will be shown afterwards.
1382
1383 ![Price is shown next to the ShipStation shipping option](https://res.cloudinary.com/dza7lstvk/image/upload/v1734528106/Medusa%20Resources/Screenshot_2024-12-18_at_3.19.14_PM_smrzae.png)
1384
1385 7. Click on the ShipStation option, then click Continue to Payment.
1386 8. Finish the payment step, then click Place order in the Review section
1387
1388 You've now created an order that uses a shipping option from ShipStation.
1389
1390 ### Fulfill Order in Admin
1391
1392 You'll now manage the order you've created in the admin to fulfill it:
1393
1394 1. Open the admin at `http://localhost:9000/app` and login.
1395 2. You'll find on the Orders page the order you've created. Click on it to view its details.
1396 3. On the order's details page, scroll down to the Unfulfilled Items section. Then, click on the three-dots icon at the top right of the section and choose "Fulfill items" from the dropdown.
1397
1398 ![In the Unfulfilled Items section, click on the three dots, then Fulfill items from the dropdown](https://res.cloudinary.com/dza7lstvk/image/upload/v1734530779/Medusa%20Resources/Screenshot_2024-12-18_at_4.05.29_PM_z9lwsk.png)
1399
1400 4. In the form that opens, choose the Location to fulfill the item(s) from, then click Create Fulfillment.
1401
1402 ![Choose from the dropdown the location to fulfill the items from, then click Create Fulfillment at the bottom right.](https://res.cloudinary.com/dza7lstvk/image/upload/v1734530888/Medusa%20Resources/Screenshot_2024-12-18_at_4.07.35_PM_f4h5o1.png)
1403
1404 5. The created fulfillment will be showing on the order's details page now.
1405
1406 ![Created fulfillment with details](https://res.cloudinary.com/dza7lstvk/image/upload/v1734535715/Medusa%20Resources/Screenshot_2024-12-18_at_5.28.06_PM_tsuk4a.png)
1407
1408 You can also cancel the fulfillment by clicking on the three-dots icon, then choosing Cancel from the dropdown. This will void the label in ShipStation and cancel its shipment.
1409
1410 ---
1411
1412
1413 ## Next Steps
1414
1415 You've now integrated Medusa with ShipStation. You can fulfill orders with many carriers and providers, all from a single integration and platform.
1416
1417 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth learning of all the concepts you've used in this guide and more.
1418
1419 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).