Miguel Almiron's first-half opener was cancelled out midway through the second half by Rangers debutant Sam Lammers, but the Magpies had the last laugh as Harrison Ashby headed home three minutes from time to give Eddie Howe's side victory in front of a sellout crowd in Glasgow.
The night belonged to McGregor, though, as the 41-year-old goalkeeper celebrated a memorable occasion at the club where he made over 500 appearances across two spells between 2001-2012 and 2018-2023.
McGregor, who became a free agent in June, is the first Rangers player to receive a testimonial match since John Brown back in 2001.
Both teams named strong starting lineups, with Rangers boss Michael Beale selecting three summer signings in Lammers, Kieran Dowell and Abdallah Sima, while Newcastle handed a debut to their marquee signing of the summer so far in Sandro Tonali, who joined from AC Milan for £55m last month.
Tonali made a confident start for the Magpies on the right of a three-man midfield next to Sean Longstaff and Elliot Anderson, and it was the Italian who started a move resulting in the opening goal on the 16-minute mark, as his controlled past through to Almiron was calmly slotted into the far corner by the winger.
Rangers struggled to get going and failed to create any decent opportunities until just after the half-hour mark when Lammers fired their first effort on target - a long-range strike straight down the throat of Newcastle goalkeeper Loris Karius.
McGregor came off to a standing ovation in the 38th minute and bid farewell to the Ibrox faithful for the final time, with summer signing Jack Butland coming on to make his debut.
Newcastle deservedly entered the half-time interval ahead to the delight of the 8,000 travelling away supporters, and after a host of changes from both sides, the Magpies continued to control proceedings and put Rangers' backline under pressure with a high press.
However, Newcastle failed to take advantage of their dominance and allowed Rangers back into the contest in the 64th minute, with substitute Bruno Guimaraes caught in possession by Lammers on the edge of the area before the Gers striker squeezed the ball beyond Karl Darlow.
Both teams continued to freshen up their sides with more substitutions, and it was the unlikely source of defender Ashby, a January signing from West Ham United, who netted what proved to be the winning goal in the 87th minute with a looping header over Butland at the far post.
Rangers will continue their pre-season preparations with home friendlies against Hamburger SV and Olympiakos before travelling to Germany to take on Hoffenheim.
As for Newcastle, they will now travel to the USA for the inaugural Premier League Summer Series tournament where they will face Aston Villa, Chelsea and Brighton & Hove Albion, before returning to St James' Park for encounters with Fiorentina and Villarreal.