Dupin listens to G—'s story, and suggests that G— is being a big dummy and missing something obvious.
When G— returns a month later, Dupin just happens to have the letter. He hands it over and gets a check for fifty thousand franks in exchange.
After G— leaves, Dupin tells the narrator that he tries to get inside people's heads in order to figure out how they might behave in a given situation.
He describes using this technique to help himself see that D— was hiding the letter in an obvious place.
When he figured it out, he strolled over to D—'s, located the letter, and then contrived to return the next day and exchange it for a copy he'd created.
Turns out, he and D— are rivals, and that he didn't steal the letter back just for money or because he liked the queen.
Nope, he also wanted to get revenge on D— for some unspecified past "evil" (122).
To make sure D— understands that it was Dupin who took the letter, he leaves D— a message inside the fake letter.