Purgatory's usual proof text is 2 Maccabees 12:38-46, where Judas Maccabeus takes up a collection to offer a sin offering for fallen soldiers found wearing forbidden amulets, "that they might be delivered from their sin." The book is deuterocanonical, accepted as scripture by Catholics and Orthodox and excluded by the Reformers' canon, which is part of why the same text does not settle the argument between them.
Prayer for the dead is attested very early and widely, in inscriptions, in the liturgies, and in patristic writers including Tertullian, Cyprian and Augustine, well before any developed doctrine of a purgatorial state existed to explain why such prayer should help. Augustine speculated cautiously about a cleansing fire for minor faults without committing to a defined place or process; Gregory the Great, two centuries later, wrote more confidently of a purifying fire before judgment for slight sins.
The doctrine hardened in the medieval West alongside a developing theology of penance: sins forgiven in confession could still carry a temporal punishment, to be worked off in this life or the next, and an indulgence was the church's grant, from a treasury of merit built up by Christ and the saints, remitting some of that punishment. Dante's Purgatorio gave the state its most vivid popular picture, a mountain of ascending terraces, though the poem is imaginative literature and was never doctrine.
The system's abuse, indulgences sold to fund the rebuilding of St Peter's, prompted by the preaching of Johann Tetzel, is what Martin Luther's ninety-five theses of 1517 directly attacked, making purgatory's supporting economy, rather than the state of the dead as such, the spark of the Reformation split.