I understand that one common cause of this sort of thing is a buildup of gunk in the latch mechanism, generally where the hooks on the door connect into the main part of the microwave. Disassembling enough to get at it and clean it up should cure it if that is the problem. (If it's not gunk, it's clearly some sort of wear or misalignment of the door vis-a-vis the latch mechanism, and examination and adjustment would still be in order.)
Do be aware if you try to take the microwave apart that they can be quite hazardous due to the high power, high voltage supply for the magnetron. The high voltage capacitor can hold a deadly charge even after the microwave is turned off and unplugged. Here is
a through document on safely troubleshooting microwaave ovens that is very well worth consulting.