The Rays trailed by seven runs through seven innings and it appeared their September surge to catch the Boston Red Sox in the AL wild-card chase would come up short.
The Rays and Red Sox went into the final game of the regular season tied for the wild-card berth, Boston had a lead over Baltimore late in their game and the Rays seemed hopelessly beaten.
Tampa Bay then produced a six-run eighth inning, highlighted by Longoria's three-run homer. Dan Johnson hit a solo shot with one out in the ninth to tie it and Longoria made it a magical night with a home run in the 12th to give Tampa Bay the win.
The final homer came moments after Baltimore had completed a two-run rally in the ninth to down Boston 4-3.
The Rays will travel to Texas to open the American League Division Series Friday. It will be the second straight year the teams have met in the opening round of the playoffs. Texas eliminated Tampa Bay in five games last year en route to the World Series.
Tampa Bay won its final five games of the regular season to finish at 91-71. The Rays went 17-10 in September while making up a nine-game deficit on Boston.
New York, which closed the season with four straight losses, got both a grand slam homer and a solo shot from Mark Teixeira while building its 7-0 lead. The Yankees will open the playoffs Friday night at home against Detroit.
Jake McGee (5-2) got the win for the Rays by working the top of the 12th.
The winning home run by Longoria came off Scott Proctor (2-6), who was the 11th New York pitcher of the game.
Celebrity Families of 2014 [PHOTOS]