Leon Goretzka's early header had Bayern in front at the Allianz Arena but Niklas Sule was sent off and Robert Glatzel and Marc Schnatterer scored to give the second-tier side a shock half-time lead.
Lewandowski was benched due to illness but within 11 minutes of his introduction as a half-time substitute he had set up Thomas Muller and turned in from close range to put Bayern ahead.
Serge Gnabry seemingly ended Heidenheim's hopes by converting a corner but Franck Schmidt's men improbably hit back with Glatzel scoring twice to draw the scores level at 4-4 and complete his hat-trick.
There was more drama to come, though, as referee Guido Winkmann harshly pointed to the spot when Marnon Busch hand-balled in the box, Lewandowski staying calm to settle matters with six minutes to play.
Bayern join RB Leipzig and Hamburg in the draw for the semi-finals, but this was more exertion than Niko Kovac would have wanted ahead of the crunch clash with Bundesliga title rival Borussia Dortmund.