Amazon.com Inc. is buying online pharmacy PillPack Inc. giving the e-commerce giant the ability to ship prescriptions around the country, and overnight, making it a direct threat to the more than $400 billion pharmacy business.

Amazon is paying roughly $1 billion in cash for PillPack, which presorts medications and ships them to customers’ homes in 49 U.S. states, excluding Hawaii, according to people familiar with the matter. The online retailer beat out Walmart Inc., which also was in talks for the five-year-old startup,...