Arizona entered Friday's contest on a nine-game winning streak and with a six- game lead in the division. But San Francisco cooled off the Diamondbacks to pull within five games, doing so thanks in large part to Beltran.
He went 4-for-4 with a triple, the homer and three runs batted in. It was his first four-hit game of the season, and his best game since the Giants acquired him from the Mets in July.
Beltran had totaled just one homer and 20 hits in his first 20 games with San Francisco, and spent time on the disabled list.
Cain (11-9) limited Arizona to two runs on five hits and four walks, while striking out three.
Diamondbacks starter Joe Saunders (9-12) allowed four runs in 5 1/3 innings to take the loss.