Using a dialplan hook, set a hangup handler on the channel and then do whatever you need to do post hangup.