I'd like to programmatically automate making a purchase on Amazon from my rails app as I have to manually make the same purchases week after week. This would be using my own billing information/account, not on behalf of a user.
I've searched through most of their APIs and found that you can search for an item, add it to a cart, etc. but I can't seem to find a way to actually make the purchase.
Does anyone know of a way to do this via API? It'd be great automate our manual process. It seems like it should be possible as https://zincapi.com/ seems to facilitate this.
You can do this, just not via the API. Instead, use:
As neatly described in their docs:
The Mechanize library is used for automating interaction with websites. Mechanize automatically stores and sends cookies, follows redirects, and can follow links and submit forms. Form fields can be populated and submitted.
You can program an advanced web crawler which
I will suggest some logic and describe the process roughly. It would be beyond the scope of the question to explain everything in detail. Be prepared for a lot of digging.
1. Add your Crawler
Dig right into Mechanize. Learn how to login to your site, search for links, press buttons and all that neat stuff. It is built upon Nokogiri which uses CSS selectors. It may take a while to grasp, but it is worth the sweat!
Also, split up the logic of the single tasks into different methods. Something like
class AmazonCrawler
attr_accessor :agent
def initialize
@agent = Mechanize.new
end
def login
agent.get(LOGIN_PATH)
# fill in and submit the form
end
def add_item_to_basket
agent.get(ITEM_PATH)
# find 'add to basket', etc...
end
def checkout
agent.get(CHECKOUT_PATH)
# validate adress, payment and place the order
end
def place_weekly_order
AmazonCrawler.login
AmazonCrawler.add_item_to_basket
AmazonCrawler.checkout
end
end
This way, you can easily add other tasks if you may need them later
2. Add a Cronjob
To setup your weekly schedule, I'd suggest using the whenever gem. This gem makes scheduling tasks easy peasy
schedule.rb
every :sunday, :at => '12pm' do
runner "AmazonCrawler.place_weekly_order"
end
Sidenote
Ideally I would set up a specific Amazon account that only does that. You would not want the bot to checkout items which you personally have added during the week and may not be certain about purchasing yet.
Also, be sure to store your credentials in ENV variables, so they are not exposed in your code.
Conclusion
I hope this gets you going, there will be a lot of new stuff for you to learn, but it actually is a fun task and will be very rewarding when your little crawler is up and running.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With