public function execute()
 {
     if (!$this->checkRequest()) {
         return;
     }
     $code = waRequest::post('code');
     $auth_codes_model = new waApiAuthCodesModel();
     $row = $auth_codes_model->getById($code);
     if ($row) {
         // check client_id
         if ($row['client_id'] != waRequest::post('client_id')) {
             $this->response(array('error' => 'invalid_grant'));
             return;
         }
         // check expire
         if (strtotime($row['expires']) < time()) {
             $this->response(array('error' => 'invalid_grant', 'error_description' => 'Authorization code expired'));
             return;
         }
         // create token
         $token_model = new waApiTokensModel();
         $token = $token_model->getToken($row['client_id'], $row['contact_id'], $row['scope']);
         $this->response(array('access_token' => $token));
     } else {
         $this->response(array('error' => 'invalid_grant', 'error_description' => 'Invalid code: ' . $code));
     }
 }
 protected function createAuthCode()
 {
     $auth_codes_model = new waApiAuthCodesModel();
     $code = md5(microtime(true) . uniqid());
     // + 5 min
     $expires = date('Y-m-d H:i:s', time() + 300);
     $auth_codes_model->insert(array('code' => $code, 'client_id' => $this->client_id, 'contact_id' => $this->contact_id, 'scope' => waRequest::get('scope'), 'expires' => $expires));
     return $code;
 }