Defining shipping method or rate in EasyPost

1.6k views Asked by At

Okay so I have the following code in one file. This is only partial code from EasyPost the easy shipping api

$created_rates = \EasyPost\Rate::create($shipment);

$availableRates = array();

foreach($created_rates as $rate){

    $fedexR = str_replace("FEDEX_", " ", $rate->service);

    $displayS = str_replace("_", " ", $fedexR);

    $displayP = $rate->rate;

    $availableRates[] = $displayS;

}

$_SESSION['displayRates'] = $availableRates;

This then sends the user to the next step in selecting a shipping method, they are displayed like so:

<?php foreach($_SESSION['displayRates'] as $rate): ?>
     <option value="<?php echo $rate; ?>"><?php echo $rate; ?></option>
<?php endforeach; ?>

This submits to the following page:

$_SESSION['shipping_method'] = $_POST['shippingRate'];

$shipment = \EasyPost\Shipment::retrieve(array('id' => $_SESSION['shipment_id']));

$shipment->buy($shipment->rates[1]);

$_SESSION['shipment_label_url'] = $shipment->postage_label->label_url;

echo $_SESSION['shipment_label_url'];

How do I send the selected shipping rate with the EasyPost API to tell it to buy postage for that shipping method? I see

$shipment->buy($shipment->rates[1]);

And I tried doing this:

$shipment->buy($shipment->rates[$_SESSION['shipping_method']]); But the resulted in the rate not being sent at all.

BTW, the session is the actual word like "GROUND" not a number. Not sure how I can achieve this, but I must if I want it to work at all!

2

There are 2 answers

0
Gabriel Sinkin On

The shipment has a rate filter on it called lowest_rate. You can pass args to it like carrier name and service name. Something like:

$shipment->buy($shipment->lowest_rate(array('Fedex'), array($_SESSION['shipping_method'])));
0
JAX On

first you need to change the way you output the <option value="<?php echo $rate; ?>"><?php echo $rate; ?></option>

it should be more like <option value="<?php echo $rate[id]; ?>"><?php echo $rate[rate].' '.$displayS; ?></option>

You will need this rate[id] to buy the shipping label like this

$shipment->buy(array('rate'=>array('id'=>$_POST[rate_id])));

and then you can do this:

<img src="<?php echo $shipment->postage_label->label_url; ?>">