San Francisco got to Fernandez for a pair of runs in the first, as a Buster Posey sacrifice fly and Brandon Belt RBI single gave the Giants a quick 2-0 edge.
Matt Cain returned to the mound for the Giants, and Miami first got on the board in the third. Christian Yelich doubled with two outs and Adeiny Hechavarria singled to cut the Giants' lead in half.
Gregor Blanco hit a solo home run to open the fifth but Miami scored four times in the bottom of the frame. Fernandez homered to open the inning and Justin Bour hit a three run home run to right center field to make it a 5-3 contest.
Fernandez tossed six innings, allowing three runs while not walking a batter and striking out six.
Carter Capps allowed a run in the top of the eighth before A.J. Ramos saved the game for Miami in the ninth.
The Marlins head to Chicago for a weekend series against the Cubs.
Hero of The Game: Justin Bour (+.286 WPA)
Goat of The Game: Jeff Mathis (-.184 WPA)
Play of The Game: Justin Bour hit a three run home run in the fifth. (+.307 WPA)