You may need a wired keyboard to carry out some of these steps. It's a good idea to keep a cheap wired keyboard and mouse or trackball as backups for a desktop Mac anyway, because Bluetooth isn't completely reliable.
Step 1
If the keyboard is already paired with another device, remove that pairing.
Step 2
Follow the instructions inthese support articles:
How to set up your Apple Wireless Keyboard
Apple Wireless Keyboard: Difficulty during pairing process
Bluetooth devices become unresponsive
Step 3
The keyboard should pair automatically when you restart the computer. You may have to press and hold the power button on the right side of an Apple keyboard until the LED starts flashing.
Step 4
Reset the System Management Controller.
Step 5
Back up all data.
Triple-click anywhere in the line below on this page to select it:
/Library/Preferences/com.apple.Bluetooth.plist
Right-click or control-click the line and select
Services ▹ Reveal
from the contextual menu.* A folder should open with an item selected. Move the selected item to the Trash. You may be prompted for your administrator login password. Restart.
*If you don't see the contextual menu item, copy the selected text to the Clipboard by pressing the key combinationcommand-C. In the Finder, select
Go ▹ Go to Folder...
from the menu bar and paste into the box that opens by pressing command-V. You won't see what you pasted because a line break is included. Press return.
Step 6
See these support articles:
Bluetooth keyboard may not pair during Setup Assistant
Wi-Fi and Bluetooth: Potential sources of wireless interference
Bluetooth: Unreliable wireless performance may occur when USB 3.0 external devices are close
Step 7
Make a "Genius" appointment at an Apple Store, or go to another authorized service provider.