Hegeler sailed his free kick into the top corner deep in added time to earn the winner on his Champions League debut and lift Leverkusen to third in the group on three points.
The Spaniards, in the competition for the first time after a decade, levelled early in the second half with Mexican Carlos Vela scoring on the rebound after keeper Bernd Leno saved his 52nd minute penalty.
"We had a very good game in the first 20 minutes and were unlucky not to have scored then," Leverkusen sporting director Rudi Voller said.
"To win in the last minute against such a tough team is fantastic. We are still in the running."
The Germans, who won all home games in their previous two Champions League group stage appearances in 2004 and 2011, are one point behind Manchester United and Shakhtar Donetsk after they drew 1-1 in Ukraine.
"I think this is my first goal from a free kick in a competitive game," the 25-year-old Hegeler, who had come on five minutes from time, told reporters.
"It is a fantastic feeling. There were not that many free kick takers left in the game and I had scored one just like that in a friendly about three weeks ago so I said to myself 'do it again.'"
Real Sociedad, who lost their opener 2-0 against Shakhtar, are in bottom place with no points.
"We played a great game, but the last kick of the match was a major blow," said Real coach Jagoba Arrasate.
"We have done many things right in the first two match days but are still on zero points. It seems unfair, but this is the Champions League."
With Germany coach Joachim Loew in the stands to watch Stefan Kiessling with his starting strikers Miroslav Klose and Mario Gomez injured ahead of World Cup qualifiers this month, the hosts, third in the Bundesliga, enjoyed a strong start.
Kiessling and South Korea's Son Heung-min repeatedly tried to catch the slower Spaniards on the break as a hard-working Leverkusen defence quickly stifled any potential threat.
Rolfes almost grabbed a 20th minute lead but keeper Claudio Bravo did well to palm his deflected shot wide.
Chile's Bravo again came to the rescue three minutes later, stretching to turn a Sidney Sam effort wide as the Germans kept on the offensive.
It took more than half an hour for Real to balance the scales with Leverkusen's Leno twice denying their long-range efforts.
The visitors came out fighting after the break, earning a 52nd minute penalty when Vela was brought down.
The 24-year-old Mexican stepped up, saw his effort punched away by Leno but slid in to level with his team's first goal in the competition this season.
In a free-flowing final 30 minutes both teams went out in search of the winner but despite several chances on each side failed to score until Hegeler's strike at the death.
- Sports & Recreation
- Manchester United
- Bernd Leno
- Carlos Vela