WASHINGTON — President Trump backed off his plan to impose tariffs on all Mexican goods and announced via Twitter on Friday night that the United States had reached an agreement with Mexico to reduce the flow of migrants to the southwestern border.

Mr. Trump tweeted the announcement only hours after returning from Europe and following several days of intense and sometimes difficult negotiations between American and Mexican officials in Washington.

The president’s threat that he would impose potentially crippling tariffs on the United States’ largest trading partner and one of its closest allies brought both countries to the brink of an economic and diplomatic crisis — only to be yanked back from the precipice nine days later. The threat had rattled companies across North America, including automakers and agricultural firms, which have built supply chains across Mexico, the United States and Canada.

[Update: Mexico agreed to take border action months before Trump announced tariff deal.]

Businesses had warned that the tariffs would increase costs for American consumers, who import everything from cucumbers to refrigerators from Mexico, and prompt retaliation from the Mexican government in the form of new trade barriers that would damage the United States economy.