示例#1
0
        public string GetTrackingURL(ShippoSession session, IShippingContext context, string carrierID, string trackingNumber)
        {
            var url = base.GetTrackingURL(session, context, carrierID, trackingNumber);

            if (url.IsNullOrWhiteSpace() &&
                carrierID.IsNotNullOrWhiteSpace() &&
                trackingNumber.IsNotNullOrWhiteSpace())
            {
                var carrier = GetShippingCarriers(session, context).FirstOrDefault(c => c.Name.EqualsIgnoreCase(carrierID));
                if (carrier == null)
                {
                    return(null);
                }

                string ccode;
                if (!CARRIERS.TryGetValue(carrier.Type, out ccode))
                {
                    return(null);
                }

                return(URI_TRACKING_BY_NUM.Args(carrierID, trackingNumber));
            }

            return(url);
        }
示例#2
0
        private Label doCreateLabel(ShippoSession session, IShippingContext context, Shipment shipment, object labelID, Guid logID)
        {
            var cred = (ShippoCredentials)session.User.Credentials;

            // label request
            var request = new WebClient.RequestParams
            {
                Caller      = this,
                Uri         = new Uri(URI_API_BASE + URI_TRANSACTIONS),
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = getCreateLabelRequestBody(session, shipment, labelID)
            };

            var response = WebClient.GetJson(request);

            Log(MessageType.Info, "doCreateLabel()", response.ToJSON(), relatedMessageID: logID);

            checkResponse(response);

            // get label bin data from URL in response
            string labelURL = response["label_url"].AsString().EscapeURIStringWithPlus();
            string contentType;
            var    data = WebClient.GetData(new Uri(labelURL), this, out contentType);

            // get used rate, fill label's data
            var id             = response["object_id"];
            var trackingNumber = response["tracking_number"].AsString();
            var rate           = getRate(session, response["rate"].AsString(), logID);
            var carrier        = rate != null?
                                 CARRIERS.First(c => c.Value.EqualsIgnoreCase(rate["provider"].AsString())).Key:
                                 Carrier.Unknown;

            var amount = rate != null ?
                         new NFX.Financial.Amount(rate["currency"].AsString(), rate["amount"].AsDecimal()) :
                         new NFX.Financial.Amount(string.Empty, 0);

            var label = new Label(id,
                                  labelURL,
                                  data,
                                  shipment.LabelFormat,
                                  trackingNumber,
                                  carrier,
                                  amount);

            if (labelID == null)
            {
                StatCreateLabel();
            }
            else
            {
                StatCreateReturnLabel();
            }

            return(label);
        }
示例#3
0
        private JSONDataMap doGetRate(ShippoSession session, string rateID, Guid logID)
        {
            try
            {
                var cred = (ShippoCredentials)session.User.Credentials;

                var request = new WebClient.RequestParams(this)
                {
                    Method      = HTTPRequestMethod.GET,
                    ContentType = ContentType.JSON,
                    Headers     = new Dictionary <string, string>
                    {
                        { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                    }
                };

                var response = WebClient.GetJson(new Uri((URI_API_BASE + URI_RATES).Args(rateID)), request);

                checkResponse(response);

                return(response);
            }
            catch (Exception ex)
            {
                var error = ShippingException.ComposeError(ex.Message, ex);
                Log(MessageType.Error, "getRate()", StringConsts.SHIPPO_CREATE_LABEL_ERROR, error, relatedMessageID: logID);
                return(null);
            }
        }
示例#4
0
        private JSONDataMap getCreateLabelRequestBody(ShippoSession session, Shipment shipment)
        {
            var isReturn = shipment.LabelIDForReturn.IsNotNullOrWhiteSpace();

            var body = new JSONDataMap();

            body["carrier_account"]    = shipment.Carrier.Name;
            body["servicelevel_token"] = shipment.Service.Name;
            body["label_file_type"]    = FORMATS[shipment.LabelFormat];
            body["async"] = false;

            var shpm = new JSONDataMap();

            shpm["object_purpose"] = PURCHASE_PURPOSE;
            shpm["parcel"]         = getParcelBody(shipment);
            shpm["address_from"]   = getAddressBody(shipment.FromAddress);
            shpm["address_to"]     = getAddressBody(shipment.ToAddress);
            if (!isReturn && (shipment.ReturnAddress != null))
            {
                shpm["address_return"] = getAddressBody(shipment.ReturnAddress);
            }

            if (isReturn)
            {
                shpm["return_of"] = shipment.LabelIDForReturn;
            }

            body["shipment"] = shpm;

            return(body);
        }
示例#5
0
        private Address doValidateAddress(ShippoSession session, IShippingContext context, Address address, Guid logID, out ValidateShippingAddressException error)
        {
            error = null;
            var cred = (ShippoCredentials)session.User.Credentials;
            var body = getAddressBody(address);

            body["validate"] = true;

            // validate address request
            var request = new WebClient.RequestParams(this)
            {
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = body.ToJSON(JSONWritingOptions.Compact)
            };

            var response = WebClient.GetJson(new Uri(URI_API_BASE + URI_ADDRESS), request);

            Log(MessageType.Info, "doValidateAddress()", response.ToJSON(), relatedMessageID: logID);

            // check for validation errors:
            // Shippo API can return STATUS_INVALID or (!!!) STATUS_VALID but with 'code'="Invalid"
            var         state    = response["object_state"].AsString(STATUS_INVALID);
            var         messages = response["messages"] as JSONDataArray;
            JSONDataMap message  = null;
            var         code     = string.Empty;
            var         text     = string.Empty;

            if (messages != null)
            {
                message = messages.FirstOrDefault() as JSONDataMap;
            }
            if (message != null)
            {
                code = message["code"].AsString(string.Empty);
                text = message["text"].AsString(string.Empty);
            }

            // error found
            if (!state.EqualsIgnoreCase(STATUS_VALID) || code.EqualsIgnoreCase(CODE_INVALID))
            {
                var errMess = StringConsts.SHIPPO_VALIDATE_ADDRESS_INVALID_ERROR.Args(text);
                Log(MessageType.Error, "doValidateAddress()", errMess, relatedMessageID: logID);
                error = new ValidateShippingAddressException(errMess, text);
                return(null);
            }

            // no errors
            var corrAddress = getAddressFromJSON(response);

            return(corrAddress);
        }
示例#6
0
        public string GetTrackingURL(ShippoSession session, IShippingContext context, string carrierID, string trackingNumber)
        {
            var url = base.GetTrackingURL(session, context, carrierID, trackingNumber);

            if (url.IsNullOrWhiteSpace() &&
                carrierID.IsNotNullOrWhiteSpace() &&
                trackingNumber.IsNotNullOrWhiteSpace())
            {
                return(URI_TRACKING_BY_NUM.Args(carrierID, trackingNumber));
            }

            return(null);
        }
示例#7
0
        private Exception doValidateAddress(ShippoSession session, IShippingContext context, Address address, Guid logID)
        {
            var cred = (ShippoCredentials)session.User.Credentials;
            var body = getAddressBody(address);

            body["validate"] = true;

            // validate address request
            var request = new WebClient.RequestParams
            {
                Caller      = this,
                Uri         = new Uri(URI_API_BASE + URI_ADDRESS),
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = body.ToJSON(JSONWritingOptions.Compact)
            };

            var response = WebClient.GetJson(request);
            var state    = response["object_state"].AsString(STATUS_INVALID);

            if (state.EqualsIgnoreCase(STATUS_VALID))
            {
                return(null);
            }

            Log(MessageType.Info, "doValidateAddress()", response.ToJSON(), relatedMessageID: logID);

            // if any error
            var         messages = response["messages"] as JSONDataArray;
            JSONDataMap message  = null;

            if (messages != null)
            {
                message = messages.FirstOrDefault() as JSONDataMap;
            }

            string details = message == null ?
                             UNKNOWN_TXT :
                             "{0} - {1}".Args(message["code"].AsString(UNKNOWN_TXT), message["text"].AsString(UNKNOWN_TXT));

            Log(MessageType.Error, "doValidateAddress()", response.ToJSON(), relatedMessageID: logID);

            return(new ShippingException(StringConsts.SHIPPO_VALIDATE_ADDRESS_INVALID_ERROR.Args(details)));
        }
示例#8
0
        private string getCreateLabelRequestBody(ShippoSession session, Shipment shipment, object labelID)
        {
            shipment.CarrierID = session.ConnectionParams.CarrierID; // use USPS for the moment
            shipment.ServiceID = USPS_PRIORITY_SERVICE;

            var isReturn = labelID != null;

            var body = new JSONDataMap();

            body["carrier_account"]    = shipment.CarrierID;
            body["servicelevel_token"] = shipment.ServiceID;
            body["label_file_type"]    = FORMATS[shipment.LabelFormat];
            body["async"] = false;

            var shpm = new JSONDataMap();

            shpm["object_purpose"] = PURCHASE_LABEL_PURPOSE;
            shpm["address_from"]   = getAddressBody(shipment.FromAddress);
            shpm["address_to"]     = getAddressBody(shipment.ToAddress);
            if (!isReturn && shipment.ReturnAddress.HasValue)
            {
                shpm["address_return"] = getAddressBody(shipment.ReturnAddress.Value);
            }
            body["shipment"] = shpm;

            var parcel = new JSONDataMap();

            if (shipment.Template.HasValue)
            {
                parcel["template"] = PARCEL_TEMPLATES[shipment.Template.Value];
            }
            parcel["length"]        = shipment.Length.ToString(CultureInfo.InvariantCulture);
            parcel["width"]         = shipment.Width.ToString(CultureInfo.InvariantCulture);
            parcel["height"]        = shipment.Height.ToString(CultureInfo.InvariantCulture);
            parcel["distance_unit"] = DIST_UNITS[shipment.DistanceUnit];
            parcel["weight"]        = shipment.Weight.ToString(CultureInfo.InvariantCulture);
            parcel["mass_unit"]     = MASS_UNITS[shipment.MassUnit];

            shpm["parcel"] = parcel;

            if (isReturn)
            {
                shpm["return_of"] = labelID;
            }

            return(body.ToJSON(JSONWritingOptions.Compact));
        }
示例#9
0
        public Address ValidateAddress(ShippoSession session, IShippingContext context, Address address, out ValidateShippingAddressException error)
        {
            var logID = Log(MessageType.Info, "ValidateAddress()", StringConsts.SHIPPO_VALIDATE_ADDRESS_MESSAGE);

            try
            {
                return(doValidateAddress(session, context, address, logID, out error));
            }
            catch (Exception ex)
            {
                StatValidateAddressErrorCount();

                var header = StringConsts.SHIPPO_VALIDATE_ADDRESS_ERROR.Args(ex.ToMessageWithType());
                Log(MessageType.Error, "ValidateAddress()", header, ex, logID);
                throw ShippingException.ComposeError(ex.Message, ex);
            }
        }
示例#10
0
        private Financial.Amount?doEstimateShippingCost(ShippoSession session, IShippingContext context, Shipment shipment, Guid logID)
        {
            var cred  = (ShippoCredentials)session.User.Credentials;
            var sbody = getShipmentBody(shipment);

            // get shipping request
            var request = new WebClient.RequestParams(this)
            {
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = sbody.ToJSON(JSONWritingOptions.Compact)
            };

            var response = WebClient.GetJson(new Uri(URI_API_BASE + URI_SHIPMENTS), request);

            Log(MessageType.Info, "doEstimateShippingCost()", response.ToJSON(), relatedMessageID: logID);

            checkResponse(response);

            var rates = response["rates_list"] as JSONDataArray;

            if (rates == null)
            {
                return(null);
            }

            foreach (JSONDataMap rate in rates)
            {
                var carrierID = rate["carrier_account"].AsString();
                if (carrierID.IsNotNullOrWhiteSpace() &&
                    string.Equals(carrierID, shipment.Carrier.Name, StringComparison.InvariantCultureIgnoreCase) &&
                    string.Equals(rate["servicelevel_token"].AsString(), shipment.Method.Name, StringComparison.InvariantCultureIgnoreCase))
                {
                    return(new Financial.Amount(rate["currency_local"].AsString(), rate["amount_local"].AsDecimal()));
                }

                // todo: where is Template?! minimize cost among all mathced rates?
            }

            return(null);
        }
示例#11
0
        private Label doCreateLabel(ShippoSession session, IShippingContext context, Shipment shipment, Guid logID)
        {
            var cred = (ShippoCredentials)session.User.Credentials;

            // label request
            var request = new WebClient.RequestParams(this)
            {
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = getCreateLabelRequestBody(session, shipment).ToJSON(JSONWritingOptions.Compact)
            };

            var response = WebClient.GetJson(new Uri(URI_API_BASE + URI_TRANSACTIONS), request);

            Log(MessageType.Info, "doCreateLabel()", response.ToJSON(), relatedMessageID: logID);

            checkResponse(response);

            // get label bin data from URL in response
            string labelURL = response["label_url"].AsString().EscapeURIStringWithPlus();

            // get used rate, fill label's data
            var id             = response["object_id"].AsString();
            var trackingNumber = response["tracking_number"].AsString();
            var rate           = doGetRate(session, response["rate"].AsString(), logID);
            var amount         = rate != null ?
                                 new NFX.Financial.Amount(rate["currency"].AsString(), rate["amount"].AsDecimal()) :
                                 new NFX.Financial.Amount(string.Empty, 0);

            var label = new Label(id,
                                  labelURL,
                                  shipment.LabelFormat,
                                  trackingNumber,
                                  shipment.Carrier.Type,
                                  amount);

            StatCreateLabel();

            return(label);
        }
示例#12
0
        public ShippingRate EstimateShippingCost(ShippoSession session, IShippingContext context, Shipment shipment)
        {
            var logID = Log(MessageType.Info, "EstimateShippingCost()", StringConsts.SHIPPO_ESTIMATE_SHIPPING_COST_MESSAGE.Args(shipment.FromAddress, shipment.ToAddress, shipment.Service.Name));

            try
            {
                return(doEstimateShippingCost(session, context, shipment, logID));
            }
            catch (Exception ex)
            {
                StatEstimateShippingCostErrorCount();

                var header = StringConsts.SHIPPO_ESTIMATE_SHIPPING_COST_ERROR.Args(shipment.FromAddress, shipment.ToAddress, shipment.Service.Name, ex.ToMessageWithType());
                Log(MessageType.Error, "EstimateShippingCost()", header, ex, logID);
                var error = ShippingException.ComposeError(ex.Message, ex);

                throw error;
            }
        }
示例#13
0
        public Label CreateLabel(ShippoSession session, IShippingContext context, Shipment shipment)
        {
            var logID = Log(MessageType.Info, "CreateLabel()", StringConsts.SHIPPO_CREATE_LABEL_MESSAGE.Args(shipment.FromAddress, shipment.ToAddress));

            try
            {
                return(doCreateLabel(session, context, shipment, logID));
            }
            catch (Exception ex)
            {
                StatCreateLabelError();

                var header = StringConsts.SHIPPO_CREATE_LABEL_ERROR.Args(shipment.FromAddress, shipment.ToAddress, ex.ToMessageWithType());
                Log(MessageType.Error, "CreateLabel()", header, ex, logID);
                var error = ShippingException.ComposeError(ex.Message, ex);

                throw error;
            }
        }
示例#14
0
        public TrackInfo TrackShipment(ShippoSession session, IShippingContext context, string trackingNumber) // carrier ID???
        {
            var logID = Log(MessageType.Info, "TrackShipment()", StringConsts.SHIPPO_TRACK_SHIPMENT_MESSAGE.Args(trackingNumber));

            try
            {
                return(doTrackShipment(session, context, trackingNumber, logID));
            }
            catch (Exception ex)
            {
                StatTrackShipmentErrorCount();

                var header = StringConsts.SHIPPO_TRACK_SHIPMENT_ERROR.Args(trackingNumber, ex.ToMessageWithType());
                Log(MessageType.Error, "TrackShipment()", header, ex, logID);
                var error = ShippingException.ComposeError(ex.Message, ex);

                throw error;
            }
        }
示例#15
0
        private ShippingRate doEstimateShippingCost(ShippoSession session, IShippingContext context, Shipment shipment, Guid logID)
        {
            var cred  = (ShippoCredentials)session.User.Credentials;
            var sbody = getShipmentBody(shipment);

            // get shipping request
            var request = new WebClient.RequestParams(this)
            {
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = sbody.ToJSON(JSONWritingOptions.Compact)
            };

            var response = WebClient.GetJson(new Uri(URI_API_BASE + URI_SHIPMENTS), request);

            Log(MessageType.Info, "doEstimateShippingCost()", response.ToJSON(), relatedMessageID: logID);

            checkResponse(response);

            var rates = response["rates_list"] as JSONDataArray;

            if (rates == null)
            {
                return(null);
            }

            var bestApprRate = new ShippingRate
            {
                CarrierID = shipment.Carrier.Name,
                ServiceID = shipment.Service.Name,
                PackageID = shipment.Package != null ? shipment.Package.Name : null
            };
            var bestAltRate = new ShippingRate
            {
                CarrierID     = shipment.Carrier.Name,
                ServiceID     = shipment.Service.Name,
                PackageID     = shipment.Package != null ? shipment.Package.Name : null,
                IsAlternative = true
            };

            // try to find rate with requested carrier/service/package (i.e. "appropriate") with the best price
            // if no appropriate rate found, return alternative rate (also with the best price)
            foreach (JSONDataMap rate in rates)
            {
                var carrierID = rate["carrier_account"].AsString();
                var serviceID = rate["servicelevel_token"].AsString();
                var cost      = new Financial.Amount(rate["currency_local"].AsString(), rate["amount_local"].AsDecimal());

                if (shipment.Carrier.Name.EqualsIgnoreCase(carrierID) &&
                    shipment.Service.Name.EqualsIgnoreCase(serviceID))
                {
                    if (bestApprRate.Cost == null ||
                        (bestApprRate.Cost.Value.CurrencyISO.EqualsIgnoreCase(cost.CurrencyISO) && // todo: multiple currencies
                         bestApprRate.Cost.Value.Value > cost.Value))
                    {
                        bestApprRate.Cost = cost;
                    }
                }

                if (bestAltRate.Cost == null ||
                    (bestAltRate.Cost.Value.CurrencyISO.EqualsIgnoreCase(cost.CurrencyISO) && // todo: multiple currencies
                     bestAltRate.Cost.Value.Value > cost.Value))
                {
                    bestAltRate.Cost = cost;
                }
            }

            return((bestApprRate.Cost != null) ? bestApprRate : bestAltRate);
        }
示例#16
0
        private Label doCreateLabel(ShippoSession session, IShippingContext context, Shipment shipment, object labelID, Guid logID)
        {
            var cred = (ShippoCredentials)session.User.Credentials;

            // label request
            var request = new WebClient.RequestParams
            {
              Caller = this,
              Uri = new Uri(URI_API_BASE + URI_TRANSACTIONS),
              Method = HTTPRequestMethod.POST,
              ContentType = ContentType.JSON,
              Headers = new Dictionary<string, string>
            {
              { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
            },
              Body = getCreateLabelRequestBody(session, shipment, labelID)
            };

            var response = WebClient.GetJson(request);

            Log(MessageType.Info, "doCreateLabel()", response.ToJSON(), relatedMessageID: logID);

            checkResponse(response);

            // get label bin data from URL in response
            string labelURL = response["label_url"].AsString().EscapeURIStringWithPlus();
            string contentType;
            var data = WebClient.GetData(new Uri(labelURL), this, out contentType);

            // get used rate, fill label's data
            var id = response["object_id"];
            var trackingNumber = response["tracking_number"].AsString();
            var rate = getRate(session, response["rate"].AsString(), logID);
            var carrier = rate != null ?
                      CARRIERS.First(c => c.Value.EqualsIgnoreCase(rate["provider"].AsString())).Key :
                      Carrier.Unknown;
            var amount = rate != null ?
                     new NFX.Financial.Amount(rate["currency"].AsString(), rate["amount"].AsDecimal()) :
                     new NFX.Financial.Amount(string.Empty, 0);

            var label = new Label(id,
                              labelURL,
                              data,
                              shipment.LabelFormat,
                              trackingNumber,
                              carrier,
                              amount);

            if (labelID == null) StatCreateLabel();
            else StatCreateReturnLabel();

            return label;
        }
示例#17
0
        private TrackInfo doTrackShipment(ShippoSession session, IShippingContext context, string carrierID, string trackingNumber, Guid logID)
        {
            if (trackingNumber.IsNullOrWhiteSpace())
            {
                throw new ShippingException("Tracking number is empty");
            }

            var carrier = GetShippingCarriers(session, context).FirstOrDefault(c => c.Name.EqualsIgnoreCase(carrierID));

            if (carrier == null)
            {
                throw new ShippingException("Unknown carrier");
            }

            string ccode;

            if (!CARRIERS.TryGetValue(carrier.Type, out ccode))
            {
                throw new ShippingException("Unknown carrier");
            }

            var cred = (ShippoCredentials)session.User.Credentials;

            var request = new WebClient.RequestParams(this)
            {
                Method      = HTTPRequestMethod.GET,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                }
            };

            var response = WebClient.GetJson(new Uri((URI_API_BASE + URI_TRACKING).Args(ccode, trackingNumber)), request);

            var result = new TrackInfo();

            var status = response["tracking_status"] as JSONDataMap;

            if (status == null)
            {
                throw new ShippingException("Tracking status is not available");
            }

            TrackStatus ts;

            if (status["status"] != null && TRACK_STATUSES.TryGetValue(status["status"].AsString(), out ts))
            {
                result.Status = ts;
            }

            DateTime date;

            if (status["status_date"] != null && DateTime.TryParse(status["status_date"].AsString(), out date))
            {
                result.Date = date;
            }

            result.Details         = status["status_details"].AsString();
            result.CurrentLocation = getAddressFromJSON(status["location"] as JSONDataMap);

            var service = response["servicelevel"] as JSONDataMap;

            if (service != null)
            {
                result.ServiceID = service["name"].AsString();
            }
            result.FromAddress = getAddressFromJSON(response["address_from"] as JSONDataMap);
            result.ToAddress   = getAddressFromJSON(response["address_to"] as JSONDataMap);

            var history = response["tracking_history"] as JSONDataArray;

            if (history != null)
            {
                foreach (JSONDataMap hitem in history)
                {
                    var hi = new TrackInfo.HistoryItem();

                    if (hitem["status"] != null && TRACK_STATUSES.TryGetValue(hitem["status"].AsString(), out ts))
                    {
                        hi.Status = ts;
                    }

                    hi.Details = hitem["status_details"].AsString();

                    if (hitem["status_date"] != null && DateTime.TryParse(hitem["status_date"].AsString(), out date))
                    {
                        hi.Date = date;
                    }

                    hi.CurrentLocation = getAddressFromJSON(hitem["location"] as JSONDataMap);

                    result.History.Add(hi);
                }
            }

            return(result);
        }
示例#18
0
        public Label CreateLabel(ShippoSession session, IShippingContext context, Shipment shipment)
        {
            var logID = Log(MessageType.Info, "CreateLabel()", StringConsts.SHIPPO_CREATE_LABEL_MESSAGE.Args(shipment.FromAddress, shipment.ToAddress));

            try
            {
              return doCreateLabel(session, context, shipment, null, logID);
            }
            catch (Exception ex)
            {
              StatCreateLabelError();

              var header = StringConsts.SHIPPO_CREATE_LABEL_ERROR.Args(shipment.FromAddress, shipment.ToAddress, ex.ToMessageWithType());
              Log(MessageType.Error, "CreateLabel()", header, ex, logID);
              var error = ShippingException.ComposeError(ex.Message, ex);

              throw error;
            }
        }
示例#19
0
 private TrackInfo doTrackShipment(ShippoSession session, IShippingContext context, string trackingNumber, Guid logID)
 {
     throw new NotImplementedException();
 }
示例#20
0
        private string getCreateLabelRequestBody(ShippoSession session, Shipment shipment, object labelID)
        {
            shipment.CarrierID = session.ConnectionParams.CarrierID; // use USPS for the moment
            shipment.ServiceID = USPS_PRIORITY_SERVICE;

            var isReturn = labelID != null;

            var body = new JSONDataMap();
            body["carrier_account"] = shipment.CarrierID;
            body["servicelevel_token"] = shipment.ServiceID;
            body["label_file_type"] = FORMATS[shipment.LabelFormat];
            body["async"] = false;

            var shpm = new JSONDataMap();
            shpm["object_purpose"] = PURCHASE_LABEL_PURPOSE;
            shpm["address_from"] = getAddressBody(shipment.FromAddress);
            shpm["address_to"] = getAddressBody(shipment.ToAddress);
            if (!isReturn && shipment.ReturnAddress.HasValue)
              shpm["address_return"] = getAddressBody(shipment.ReturnAddress.Value);
            body["shipment"] = shpm;

            var parcel = new JSONDataMap();
            if (shipment.Template.HasValue)
              parcel["template"] = PARCEL_TEMPLATES[shipment.Template.Value];
            parcel["length"] = shipment.Length.ToString(CultureInfo.InvariantCulture);
            parcel["width"] = shipment.Width.ToString(CultureInfo.InvariantCulture);
            parcel["height"] = shipment.Height.ToString(CultureInfo.InvariantCulture);
            parcel["distance_unit"] = DIST_UNITS[shipment.DistanceUnit];
            parcel["weight"] = shipment.Weight.ToString(CultureInfo.InvariantCulture);
            parcel["mass_unit"] = MASS_UNITS[shipment.MassUnit];

            shpm["parcel"] = parcel;

            if (isReturn) shpm["return_of"] = labelID;

            return body.ToJSON(JSONWritingOptions.Compact);
        }
示例#21
0
        // carrier ID???
        public TrackInfo TrackShipment(ShippoSession session, IShippingContext context, string trackingNumber)
        {
            var logID = Log(MessageType.Info, "TrackShipment()", StringConsts.SHIPPO_TRACK_SHIPMENT_MESSAGE.Args(trackingNumber));

            try
            {
              return doTrackShipment(session, context, trackingNumber, logID);
            }
            catch (Exception ex)
            {
              StatCreateLabelError();

              var header = StringConsts.SHIPPO_TRACK_SHIPMENT_ERROR.Args(trackingNumber,ex.ToMessageWithType());
              Log(MessageType.Error, "TrackShipment()", header, ex, logID);
              var error = ShippingException.ComposeError(ex.Message, ex);

              throw error;
            }
        }
示例#22
0
 private TrackInfo doTrackShipment(ShippoSession session, IShippingContext context, string trackingNumber, Guid logID)
 {
     throw new NotImplementedException();
 }
示例#23
0
        private JSONDataMap getRate(ShippoSession session, string rateID, Guid logID)
        {
            try
            {
              var cred = (ShippoCredentials)session.User.Credentials;

              var request = new WebClient.RequestParams
              {
            Caller = this,
            Uri = new Uri((URI_API_BASE + URI_RATES).Args(rateID)),
            Method = HTTPRequestMethod.GET,
            ContentType = ContentType.JSON,
            Headers = new Dictionary<string, string>
              {
                { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
              }
              };

              return WebClient.GetJson(request);
            }
            catch (Exception ex)
            {
              var error = ShippingException.ComposeError(ex.Message, ex);
              Log(MessageType.Error, "getRate()", StringConsts.SHIPPO_CREATE_LABEL_ERROR, error, relatedMessageID: logID);
              return null;
            }
        }