Integrating distributed generation (DG) into the main grid is a challenge for the safety and stability of the grid. The application of peer-to-peer (P2P) technology in microgrids with distributed generation is expected to facilitate increased self-consumption of distributed and renewable energy, and the rise of prosumers’ monetary benefits. A P2P energy trading model in microgrids with photovoltaic (PV) distributed generation and battery energy storage systems (BESSs) is proposed in this paper. We additionally designed a P2P electricity trading mechanism based on coalition game theory. A simulation framework of this model is presented which assumed a local community with 30 households under comprehensive constraints encompassing a customer load profile, PV system, BESSs, market signals including feed-in tariffs, and retail prices. Firstly, individual customers can post orders (purchasing orders or selling orders) and exchange information in a P2P energy trading market. Secondly, the microgrid operator can validate the orders based on how to achieve the minimum overall energy consumption in microgrids and set reasonable real-time purchasing and selling prices for P2P energy transactions. Thirdly, the orders can be automatically conducted and completed at the designed optimal price. This mechanism can be a practical solution motivating individual customers to participate in P2P electricity trading, assist with electricity cost reduction, benefit from electricity supply increases, and help the grid operators to make the most economically and socially friendly decisions.