When you create a button the last argument in the CreateFrame function is a template. You need to put there "SecureActionButtonTemplate". Here is an example:
Code:
button = CreateFrame("BUTTON", name, parent, "SecureActionButtonTemplate")
Then you can use SetAttribute to set specific attributes of this templete. This allows you to decide what kind of actoin or spell will be assigned to the button. For your purpose you can use "spell" attribute:
Code:
button:SetAttribute("type", "spell")
button:SetAttribute("spell", spellname)
You check more, including various attributes, here:
https://wow.gamepedia.com/SecureActionButtonTemplate