Chicago had a three-game winning streak come to an end, but not before throwing a scare into the Giants.
San Francisco took a 4-0 lead into the ninth and Madison Bumgarner came out in hopes of nailing down the first shutout of his four-year major league career.
Casilla then gave way to Lopez, a 10-year veteran who is with his sixth team.
Lopez needed just four pitches to secure the victory, getting Steve Clevenger on a grounder to first that advanced the runners and David DeJesus on a fly ball to center. It was the first save of the season for Lopez and just the sixth of his career.
Buster Posey drove in two of the San Francisco runs with a sacrifice fly in the first and a single in the third.
Bumgarner (6-4) gave up two runs on eight hits with 11 strikeouts to claim the win.
Paul Maholm (4-4) was charged with the loss, allowing four runs on eight hits in 5 1/3 innings.
NY rabbi using karate to attack the 'knockout game'
Michelle Rodriguez breaks silence on Paul Walker's death