Endorphins, the bodys natural opioid-like neurotransmitters/hormones primarily regulate the body's perception of pain, stress responses, temperature and emotions.
Now imagine if you dramatically reduced the amount of them in your body (which is exactly what external opioids like Heroin do) and then you'll have your answer.
Why does it happen ? Because the body is always seeking balance (homeostasis) and adding extra synthetic opioids in = natural opiods taken out, because the body sees them as one and the same.
It all comes into play when your external supply is interrupted.
Simple.
In more technical terms:
Opioids bind to the same receptors that endorphins normally activate. With repeated use, the brain adapts by reducing receptor responsiveness and shifting other stress systems upward to compensate. When the drug is removed, the system is left in an overcorrected state, which produces withdrawal symptoms.