Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample integration of EasyPost with Stripe Relay.
require 'stripe'
require 'easypost'
Stripe.api_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
EasyPost.api_key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
SHIPPING_ORIGIN_ADDRESS = {
company: "EasyPost",
street1: "417 Montgomery St",
street2: "5 FL",
city: "SAN FRANCISCO",
state: "CA",
zip: "94104"
}
def select_easypost_rate_for_stripe_order(order, shipment)
if order.selected_shipping_method && order.selected_shipping_method.start_with?("rate_")
EasyPost::Rate.new(order.selected_shipping_method)
else
shipment.lowest_rate("USPS")
end
end
def easypost_shipment_from_stripe_order(order)
EasyPost::Shipment.create(
from_address: SHIPPING_ORIGIN_ADDRESS,
to_address: easypost_address_from_stripe_shipping(order.shipping),
parcel: {predefined_package: "PARCEL", weight: stripe_order_weight(order)},
options: {label_format: "PDF"} # custom options
)
end
def easypost_address_from_stripe_shipping(shipping)
{
name: shipping.name,
phone: shipping.phone,
street1: shipping.address.line1,
street2: shipping.address.line2,
city: shipping.address.city,
state: shipping.address.state,
zip: shipping.address.postal_code,
country: shipping.address.country
}
end
def stripe_order_weight(order)
weight = 0
order.items.each do |item|
next unless item.type == "sku"
sku = Stripe::SKU.retrieve(id: item.parent, expand: ['product'])
package_dimensions = sku.package_dimensions || sku.product.package_dimensions || {weight: 0}
weight += package_dimensions[:weight]
end
weight
end
def main
Stripe::Order.list(status: "paid", limit: 10).data.each do |paid_order|
paid_order_list.data.each do |paid_order|
puts "\nFulfilling #{paid_order.id}..."
# the Stripe Order.id is automatically sent to EasyPost as a Shipment.reference
shipment = EasyPost::Shipment.retrieve(paid_order.id)
# alternatively: the easypost_shipment_from_stripe_order method can be used to
# create an EasyPost shipment from a Stripe order.
# shipment = easypost_shipment_from_stripe_order(paid_order)
selected_rate = select_easypost_rate_for_stripe_order(paid_order, shipment)
begin
shipment.buy(selected_rate)
rescue EasyPost::Error => e
puts "Unable to fulfill #{paid_order.id}: #{e.message}"
next
end
puts "Tracking code: #{shipment.tracking_code}"
puts "Shipping label: #{shipment.postage_label.label_url}"
paid_order.status = "fulfilled"
paid_order.metadata["shipping_tracking_code"] = shipment.tracking_code
paid_order.save
end
end
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.