HELP:selling digital game keys from website

I have been trying to do this for a while and i cant get help anywhere, ive seen it done but dont know how. pre much after a buyer purchases from my website the email that is sent to then after confirmation i want it too include a game key for the game they choose but each time someone purchases that code needs to be replaced with a new one for the next customer that buys that game.