The decisive boot was set up when Su'a Cravens picked off Cardinal quarterback Kevin Hogan with 3:02 remaining.
On the next play, Trojans quarterback Cody Kessler threw a long, incomplete pass to Marqise Lee, who was hurt on the play.
With 1:23 remaining, USC faced a fourth-and-2 at the Stanford 48-yard line and Coach Ed Orgeron elected to go for it, calling on Lee to re-enter the game.
Kessler hit him with 13-yard completion for a crucial first down.
Heidari followed with his field goal six plays later and USC (8-3, 5-2 Pac-12) had the upset win.
Kessler completed 25-of-37 passes for 288 yards with a touchdown.
Hogan went 14-of-25 for 127 yards and was intercepted twice for the Cardinal (8-2, 6-2).