Pablo Sandoval also drove in two runs for the Giants, a day after they outslugged Miami 14-10.
Giancarlo Stanton hit a two-run home run for Miami.
Cain (8-8) allowed two runs and four hits. He struck out five and walked two.
Sergio Romo pitched the ninth for his 30th save in 34 chances.
Henderson Alvarez (2-2) allowed four runs, four hits and four walks while striking out four in seven innings.
Source: Associated Press