Denis Cheryshev gave the visitors the lead at Camp Nou, but Neymar levelled shortly before half-time. Villarreal then took the lead for a second time through Luciano Vietto, before Rafinha scored his first goal for the club on 53 minutes.
Messi then completed Barca's comeback and spared their blushes with the winner two minutes later, leaving Rafinha to praise his team-mates for their attacking efforts.
"We knew it was going to be difficult and they came on strong," said the Brazilian, whose strike was his first for the club. "It was a very important match for me, though I know it's difficult to win a starting position.
"Luckily we equalised quickly after going behind and then scored a third soon after. With the three players we have up front, anything is possible."
The win leaves Barcelona just a single point behind leaders Real Madrid at the top of La Liga, who have played a game less.