arriving the landing city A first and complete those immigration document at the custom gate and then fly to your destination city B. Leave a little more hours between the arrival flight and leaving flight so you have enough time to finish the landing procedure.