I wrote a component for Joomla that site users can book an appointment I want to execute the php code when the user leaves the site so that if the operation is not successful, the payment of that booking will be deleted from the database.
You should develop a User plugin and use Joomla events for firing your codes on related events. https://docs.joomla.org/Plugin/Events/User
onUserLogout
This event is triggered before the user is logged out of the system.
If any plugin returns false, the global logout fails and the onUserLogoutFailure event is fired; if it succeeds, onUserAfterLogout event is triggered instead.
Also you can find a complete tutorial about developing a plugin here: https://docs.joomla.org/J3.x:Creating_a_Plugin_for_Joomla