Didn't we see his spine get yanked out by Prime in the previous movie?
While it is true that Megatron had his head ripped off at the end of Dark of the Moon, Megatron was resurrected (sort of) in Age of Extinction as "Galvatron".
Galvatron was made from Transformium (possibly from Megatron's body) and was hooked up to Megatron's severed, but functioning head. Each of the five Galvatrons built by KSI exhibited tendencies to shift into a Megatron-like appearance. Before the deployment of the fifth and final Galvatron body, Megatron transferred his mind into the body, effectively reviving himself into a new body.
At the end of AoE, the final Galvatron/Megatron is left alive, swearing his revenge. It is this last copy that somehow makes contact with Quintessa before the events of The Last Knight.