Amazon Fresh API: PHP/cURL Woes and a Final Solution! – July 29, 2020

I just spent four hours trying to get the Amazon API to work properly.  The documentation is pretty poor, and just has the one example, which as I finally figured out in the end, works completely differently than the "landing" URL, which is the one you actually need to use.

How I thought it would work is that I would send my ingredients off to Amazon and they would return a customized link (in the form of the green button like on the verify page) and then I could display that to the visitors.  So, I worked on cURL using various methodologies of encoding, etc. and when it finally started to work, I realized that Amazon doesn't actually return the HTML for a form or button, but the whole HTML of the page, so what they really want you to do is to setup an HTML form on your page with a hidden input and then have the user press on the submit button and hope for the best (rather than me see if the items are available and in stock, etc, and provide a better user experience for the visitor).

So, without further ado, here is the code you want to take a PHP array of ingredients and display an HTML form that your visitor can click on to link to Amazon's Fresh API.

 

$list = array();
foreach($ingredients as $ingredient) {
   $list[] = array("name" => $ingredient['name'],
                        "quantityList" => array(array("unit" => $measurement = $ingredient['measurement'],"amount" => $ingredient['amount'])));
}
$result = '<form method="POST" action="https://www.amazon.com/afx/ingredients/landing">'.
     '<input type="hidden" name="ingredients" value=\''.json_encode(array("ingredients" => $list)).'\'>'.
     '<input type="submit" value="Buy on Amazon">'.
   '</form>';

 

As always, if you are looking for a professional developer to help you get your projects done, I'm available for consulting.


Questions? Have Anything to Add?
(your comments will be published on this site - click here for private questions)