Amla (122) and De Villiers (128) shared a world record third wicket partnership of 238 as South Africa made 343 for five after being sent in.
Pakistan, who were bowled out for 309 to slip 2-1 down in the series, had been in deep trouble when Afridi walked in at 132 for five but he gave his side hope as he thrashed 88 off 48 balls with seven sixes and five fours.
Afridi’s innings included some of the biggest sixes seen at the Wanderers. One, after he had been bowled off a no-ball, was a mighty hit onto the roof of the four-tier Centenary stand which was last seen bouncing towards an adjacent golf course. Afridi was yorked by Ryan McLaren when he had 73 but a check requested by umpire Billy Bowden showed the bowler had over-stepped.
Amla and De Villiers batted superbly after South Africa struggled early on, with left-arm fast bowler Mohammad Irfan taking two early wickets. They beat by one run the previous one-day international third wicket record set by Rahul Dravid and Sachin Tendulkar for India against Kenya in 1999, to ensure that Pakistan would have a challenging run chase on a ground renowned for high scoring.
The rate slowed slightly when Pakistan brought their spin bowlers into action. After 25 overs the total was 115 but the runs came in a torrent towards the end of the innings. The last 15 overs yielded 156 runs. Amla reached his 11th one-day international century off 99 balls, while De Villiers went to his 14th century in the format off 87 deliveries.