We have measured the gamma-ray emission spectrum of the Moon using the data collected by the Large Area Telescope onboard the Fermi satellite during its first 7 years of operation, in the energy range from 30 MeV up to a few GeV. We have also studied the time evolution of the flux, finding a correlation with the solar activity. We have developed a full Monte Carlo simulation describing the interactions of cosmic rays with the lunar surface. The results of the present analysis can be explained in the framework of this model, where the production of gamma rays is due to the interactions of cosmic-ray proton and helium nuclei with the surface of the Moon. Finally, we have used our simulation to derive the cosmic-ray proton and helium spectra near Earth from the Moon gamma-ray data.