Chasing a target of 246, Pakistan almost lost the plot in the last few overs. They needed 13 runs from 12 balls with four wickets in hand. But then lost three quick wickets within a space of five balls.
Afridi, however, held his nerve and smacked spinner Ravichandran Ashwin for two cosecutive sixes in the last over as Pakistan reached 249 with two balls to spare.
Pakistan got to a good start with Ahmed Shehzad (42) and Sharjeel Khan (25) adding 71 runs for the first wicket.
But after the good start, Pakistan suffered a batting collapse, as Khan, Shehzad, skipper Misbah-ul-Haq (1) and Umar Akmal (1) departed in quick succession to leave Pakistan at 113/4.
Mohammed Hafeez (75), who had also picked up two wickets with his spin, and Shoaib Maqsood (38) got Pakistan back on track with a 87-run partnership for the fifth wicket. They took Pakistan to the threshold of a win but Hafeez's dismissal in the 44th over triggered another batting collapse and from 200/4 they slumped to 236/9.