Romulo fired the five-time World Cup winners ahead, but Messi replied with two goals to give Argentina the edge.
Goals from Oscar and Hulk put Brazil in front once more, but Federico Fernandez levelled things up before Barcelona star Messi completed his treble to snatch the win and spark celebrations among the Albicelestes' fans.
The result marked Brazil's second consecutive defeat as they warm up for the London Olympics, while Argentina made the most of a bye round in the 2014 World Cup qualifiers.
Mano Menezes' side made a promising start and Neymar came close to scoring after just two minutes, combining with Leandro Damiao before unleashing a shot that fell narrowly wide of the post.
They were in front after 23 minutes though, when Romulo provided the finish to a free-kick from Neymar.
However, the Messi show began eight minutes later when he equalised following a great assist by Gonzalo Higuain.
He struck again after 34 minutes after linking up with Angel Di Maria to put Argentina ahead, but Brazil were unfortunate not to be back on level terms before the interval when Hulk's effort was brilliantly saved by Sergio Romero.
The Porto forward made amends after 56 minutes though, whipping in a cross which was poorly dealt with by Clemente Rodriguez allowing Oscar to sneak in an equaliser.
Hulk then added his name to the scoresheet after 72 minutes, volleying home a corner from Neymar.
Brazil's lead lasted just three minutes as Sergio Aguero, on as a substitute for Di Maria, fired in a corner which was powerfully headed in by Fernandez to make the scores 3-3.
Argentina - and Messi - then had the final say five minutes from time. The Barca forward completed his second hat-trick in a national team shirt with a stunning goal, racing into the centre of the pitch before smashing a shot into the top right corner.
The game ended on a sour note, however, with both Brazil defender Marcelo and Argentina forward Ezequiel Lavezzi sent off following a confrontation between the pair.