Hi Rajesh,
I agree about the environment. But if get the new object code, just after having posted the invoice, then you are 99.99% garanteed to have the correct one.
What I'm doing (had the issue seveval time, is to document.Add() the invoice and if 0 then get the object code, then generate the payment.
But if you have a time lag between the generation of the invoice, then the payment, then for sure you need an extra method to precisely determine the document to pay.
Regards,
Eric