Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining shipping method or rate in EasyPost

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!

like image 941
Mitch Evans Avatar asked Nov 26 '25 12:11

Mitch Evans


2 Answers

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'])));
like image 119
Gabriel Sinkin Avatar answered Nov 29 '25 08:11

Gabriel Sinkin


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; ?>">

like image 34
JAX Avatar answered Nov 29 '25 06:11

JAX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!