Hegeler struck in the second minute of stoppage time to secure an eighth successive win for Sami Hyypia's men at the BayArena after the visitors had come within seconds of claiming a first point of the Champions League campaign.
Former Arsenal frontman Carlos Vela had earlier fired home from close range after keeper Bernd Leno had saved his 51st-minute penalty, in the process cancelling out Bayer skipper Simon Rolfes' opener in first-half injury time.
The home side started brightly and Real goalkeeper Claudio Bravo was called upon for the first time with less than three minutes gone when he had to get down well at his near post to parry Son Heung-Min's left-foot shot.
Bravo came to the rescue once again with 21 minutes gone to keep out Rolfes' deflected snapshot, but the Spaniards enjoyed a let-off from the resulting corner when striker Stefan Kiessling met Sidney Sam's cross in front of goal, but glanced his header wide.
Opposite number Bernd Leno was almost caught out by Antoine Griezmann's 24th-minute free-kick, and he had to race from his penalty area 13 minutes before the break to head clear from Haris Seferovic as he threatened to latch on to a through-ball.
Real were starting to make their presence felt and Leno managed to beat away a long-range 34th-minute effort from Gorka Elustondo, but Son smashed a rising drive just wide of the upright at the other end three minutes later.
Kiessling went close for the Germans with two minutes of the half remaining when he blocked Mikel Gonzalez's attempted clearance, only to fire across the face of goal.
But Rolfes finally made the breakthrough with seconds of the first half remaining when he forced another save from Bravo with a bullet header, but then followed up to stab the rebound home.
However, the visitors were level within six minutes of the restart when defender Roberto Hilbert was adjudged to have tripped Vela inside the area and although Leno dived low to his left to save the striker's spot-kick, he scored at the second attempt.
Vela passed up a glorious opportunity to put his side ahead after being played in by David Zurutuza's superb 61st-minute pass, with Leno making a vital block.
Bayer substitute Robbie Kruse was guilty of failing to make the most of a gilt-edged chance as time ran down, but Hegeler spared his blushes when he despatched his last-gasp effort into the top corner.