Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help on sending tracking numbers to amazon #795

Open
katzendrama opened this issue Oct 20, 2024 · 2 comments
Open

Help on sending tracking numbers to amazon #795

katzendrama opened this issue Oct 20, 2024 · 2 comments

Comments

@katzendrama
Copy link

Hi! I am just trying to set my FBM orders as fulfilled via the selling-partner-api.

My goal is to just set an Order as fulfilled with an carrier (e.g. DHL) with an tracking number (e.g. 003404999999999).

Im not able to identify the right API for this. It could be OrdersAPI, shipping API or MerchantFulfilllmentAPI.

Im trying for weeks to find a solution. I would be happy if someone could help me :)

Thanks!

My starting point of code is this:

public function setShipped(AuftragsFulfillment $auftragsFulfillment, $amazon_id)
{

    $connector = SellingPartnerApi::seller(
        clientId: $this->amazon_clientid,
        clientSecret: $this->amazon_clientsecret,
        refreshToken: $this->amazon_refreshtoken,
        endpoint: Endpoint::EU
    );

    /*
            'tracking_info' => [
                'company' => $auftragsFulfillment->getVersandmethode() , -> DHL / Deutsche Post 
                'number' => $auftragsFulfillment->getVerfolgungsnummer(), -> 003404... / A0034567...
            ],
    */


}

`

@christian71-stack
Copy link

Look at the Mainpage of this Repository.
https://github.com/jlevers/selling-partner-api#working-with-dtos

@jordan26
Copy link

jordan26 commented Dec 6, 2024

@katzendrama - here is a copy of the function I built to handle this. I've left in all the conditionals and Sentry logging I use, feel free to remove if not needed. The link @christian71-stack referenced is also a good example.

Don't forget to change the marketplaceId

protected function sendTrackingToAmazon($data) {
        
        // If environment is development or staging, don't send stock to Amazon.
        if (WP_ENV === 'development' || WP_ENV === 'staging') {
            return;
        }

        // Process XML data into an array of shipment information
        $processedOrders = $this->processShipmentInfo($data);

        // Initialize the Selling Partner API
        $sellingPartnerApi = SellingPartnerApi::seller(
            clientId: defined('LWA_CLIENT_ID') ? LWA_CLIENT_ID : '',
            clientSecret: defined('LWA_CLIENT_SECRET') ? LWA_CLIENT_SECRET : '',
            refreshToken: defined('LWA_REFRESH_TOKEN') ? LWA_REFRESH_TOKEN : '',
            endpoint: Endpoint::EU,  // Or Endpoint::EU, Endpoint::FE, Endpoint::NA_SANDBOX, etc.
        );

        // Loop through orders and send tracking information
        foreach ($processedOrders as $amazon_order_id => $order) {
            $fulfillmentDate = new \DateTime('@' . $order['date_shipped']);
            $fulfillmentDate->setTimezone(new \DateTimeZone('UTC'));

            // Use OrdersV0Api to get order line items
            $get_line_items = $sellingPartnerApi->ordersV0()->getOrderItems($amazon_order_id);

            // JSON decode the response
            $order_line_items_array = json_decode($get_line_items->body(), true);

            // If no order line items are found, skip this order
            if ( isset( $order_line_items_array['payload']['OrderItems'] ) && empty($order_line_items_array['payload']['OrderItems']) ) {
                return;
            }

            // Create an array to store order items
            $order_items = [];

            // Loop through order line items array, and get the order item ID and quantity
            foreach ($order_line_items_array['payload']['OrderItems'] as $order_line_item) {
                $order_items[] = new Dto\ConfirmShipmentOrderItem(
                    orderItemId: $order_line_item['OrderItemId'],
                    quantity: $order_line_item['QuantityOrdered']
                );
            }

            // Remove hyphens from $amazon_order_id (exampoe: 123-4567890-1234567). Use this for the packageReferenceId. Only positive numeric values are supported, so we add a '1' to the start of the string too. As some Amazon order IDs start with 0.
            $modified_amazonOrderId = '1' . str_replace('-', '', $amazon_order_id);

            // Create ConfirmShipmentRequest DTO
            $confirmShipmentRequest = new Dto\ConfirmShipmentRequest(
                packageDetail: new Dto\PackageDetail(
                    packageReferenceId: $modified_amazonOrderId, // A seller-supplied identifier that uniquely identifies a package within the scope of an order. Only positive numeric values are supported. This is useful should you ever want to cancel or modify a shipment.
                    carrierCode: 'Hermes UK', // Identifies the carrier that will deliver the package. This field is required for all marketplaces. https://developer-docs.amazon.com/sp-api/changelog/carriercode-value-required-in-shipment-confirmations-for-br-mx-ca-sg-au-in-jp-marketplaces
                    trackingNumber: $order['tracking_number'], // The tracking number used to obtain tracking and delivery information.
                    shipDate: $fulfillmentDate, // The shipping date for the package. Must be in ISO 8601 date/time format.
                    orderItems: $order_items,
                    shippingMethod: 'Next Day', // The shipping method for the package. This field is required for all marketplaces.
                    carrierName: 'Hermes', // The name of the carrier that will deliver the package. This field is required for all marketplaces.
                ),
                marketplaceId: 'XXXXXXXXXXX' // The identifier for the marketplace where the order was placed. This helps to ensure that the correct order is confirmed.
            );

            try {
                // Send the shipment confirmation
                $sellingPartnerApi->ordersV0()->confirmShipment(
                    orderId: $amazon_order_id,
                    confirmShipmentRequest: $confirmShipmentRequest
                );

                // Sent message to Sentry on success
                // \Sentry\captureMessage('Shipment confirmed for order ' . $amazon_order_id);

            } catch (\Saloon\Exceptions\Request\ClientException $e) {
                try {
                    // Extract the response body from the exception
                    $response = $e->getResponse();
                    $responseBody = $response->body(); // Use Saloon's response body method
                    $decodedBody = json_decode($responseBody, true); // Decode JSON if needed

                    $error = $decodedBody['errors'][0]['message'] ?? 'Unknown error';
            
                    // Log the error response to Sentry
                    \Sentry\captureMessage('Response Body: ' . $error);

                } catch (\Exception $innerException) {
                    \Sentry\captureMessage('Unexpected error: ' . $innerException->getMessage());
                }
            } catch (\Exception $e) {
                // General catch for unexpected exceptions
                \Sentry\captureMessage('Unexpected error: ' . $e->getMessage());
            }
        }
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants