public function upgrade_refresh_token(system_account $systemaccount) {
        $refreshtoken = $systemaccount->get('refreshtoken');

        $params = array('refresh_token' => $refreshtoken,
            'grant_type' => 'refresh_token'
        );

        if ($this->basicauth) {
            $idsecret = urlencode($this->issuer->get('clientid')) . ':' . urlencode($this->issuer->get('clientsecret'));
            $this->setHeader('Authorization: Basic ' . base64_encode($idsecret));
        } else {
            $params['client_id'] = $this->issuer->get('clientid');
            $params['client_secret'] = $this->issuer->get('clientsecret');
        }

        // Requests can either use http GET or POST.
        if ($this->use_http_get()) {
            $response = $this->get($this->token_url(), $params);
        } else {
            $response = $this->post($this->token_url(), $this->build_post_data($params));
        }

        if ($this->info['http_code'] !== 200) {
            throw new moodle_exception('Could not upgrade oauth token');
        }

        $r = json_decode($response);

        if (!empty($r->error)) {
            throw new moodle_exception($r->error . ' ' . $r->error_description);
        }

        if (!isset($r->access_token)) {
            return false;
        }

        // Store the token an expiry time.
        $accesstoken = new stdClass;
        $accesstoken->token = $r->access_token;
        if (isset($r->expires_in)) {
            // Expires 10 seconds before actual expiry.
            $accesstoken->expires = (time() + ($r->expires_in - 10));
        }
        $accesstoken->scope = $this->scope;
        // Also add the scopes.
        $this->store_token($accesstoken);

        if (isset($r->refresh_token)) {
            $systemaccount->set('refreshtoken', $r->refresh_token);
            $systemaccount->update();
            $this->refreshtoken = $r->refresh_token;
        }

        return true;
    }