Fast bowler Shaheen Shah Afridi grabbed three wickets and star batter Babar Azam hit a half-century to guide Pakistan to a four-wicket win over South Africa in the third T20I.