Xabi Alonso scored the decider with a free kick in overtime, which was required because South Africa substitute Katlego Mphela equalized the game at 2-2 three minutes into stoppage time of regulation play.
Mphela had put Bafana Bafana ahead in the 73rd minute, but Dani Guiza scored in the 88th and 89th minutes to equalize.
"It's a nice way to forget about the loss to the U.S.," said Spain coach Vicente del Bosque, whose team's 35-game unbeaten streak was ended by the Americans with a 2-0 win in the semis. "The match was difficult for us. Our opponent created a lot of difficulties for us."
June 28 in Rustenburg
South Africa 2, Spain 3.
Goals: Mphela 73, 93+; Guiza 88, 89, Xabi Alonso 107.
South Africa - Khune, Gaxa, Mokoena, Booth, Masilela, Pienaar (Mphela 64), Sibaya, Dikgacoi, Modise (van Heerden 69), Tshabalala (Mhlongo 84, Parker.
Spain - Casillas, Arbeloa, Albiol, Pique, Capdevila, Cazorla, 1 Busquets (Llorente, 81), Xabi Alonso, Riera, Villa (Silva 57), Torres (Guiza 58).