用户同意授权后在回调url中会得到code，调用此方法用code换token以及openid，所以如果仅仅是授权openid，到这步就结束了

@param code 授权后得到的code
@return token对象
193458
public OauthGetTokenResponse getToken(String code) {
        BeanUtil.requireNonNull(code, "code is null");
        OauthGetTokenResponse response = null;
        String url = BASE_API_URL + "sns/oauth2/access_token?appid=" + this.config.getAppid() + "&secret=" + this.config.getSecret() + "&code=" + code + "&grant_type=authorization_code";
        BaseResponse r = executeGet(url);
        String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString();
        response = JSONUtil.toBean(resultJson, OauthGetTokenResponse.class);
        return response;
    }
194765
protected ModelAndView buildCallbackViewViaRedirectUri(final J2EContext context, final String clientId,
                                                           final Authentication authentication, final OAuthCode code) {
        val attributes = authentication.getAttributes();
        val state = attributes.get(OAuth20Constants.STATE).get(0).toString();
        val nonce = attributes.get(OAuth20Constants.NONCE).get(0).toString();

        val redirectUri = context.getRequestParameter(OAuth20Constants.REDIRECT_URI);
        LOGGER.debug("Authorize request verification successful for client [{}] with redirect uri [{}]", clientId, redirectUri);

        var callbackUrl = redirectUri;
        callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.CODE, code.getId());
        if (StringUtils.isNotBlank(state)) {
            callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.STATE, state);
        }
        if (StringUtils.isNotBlank(nonce)) {
            callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.NONCE, nonce);
        }
        LOGGER.debug("Redirecting to URL [{}]", callbackUrl);
        val params = new LinkedHashMap<String, String>();
        params.put(OAuth20Constants.CODE, code.getId());
        params.put(OAuth20Constants.STATE, state);
        params.put(OAuth20Constants.NONCE, nonce);
        params.put(OAuth20Constants.CLIENT_ID, clientId);
        return buildResponseModelAndView(context, servicesManager, clientId, callbackUrl, params);
    }
1300577
public function getOAuth2AccessToken($code) {
        $url = sprintf(self::OAUTH2_ACCESS_TOKEN_URL, $this->appId, $this->appSecret, $code);
        $client = $this->getHttpClient();
        $client->setUrl($url);
        $client->setHeaderArray(['Content-Type: application/json']);

        if (!$client->exec()) {
            throw new Exception("call get oauth2 access token fail");
        }

        $result = json_decode($client->getResponse(), true);
        if (!(isset($result['access_token']) && isset($result['openid']))) {
            throw new Exception("call get oauth2 access token fail url({$url}) access_token or openid is not exists, response:" . $client->getResponse());
        }

        return ['accessToken' => trim($result['access_token']), 'openId' => trim($result['openid'])];
    }
296329
def url_object(code)
      @code_bucket.get(code, :r => 1)
    rescue Riak::FailedRequest => err
      raise unless err.not_found?
    end
1260224
public function getOAuthToken($code, $token = false)
    {
        $apiData = array(
            'grant_type' => 'authorization_code',
            'client_id' => $this->getApiKey(),
            'client_secret' => $this->getApiSecret(),
            'redirect_uri' => $this->getApiCallback(),
            'code' => $code
        );

        $result = $this->_makeOAuthCall($apiData);

        return !$token ? $result : $result->access_token;
    }
479726
public function get_auth_access_token($code){

        $url = self::API_URI . self::AUTH_ACCESS_TOKEN_URI;

        $param['appid'] = $this->appid;
        $param['secret'] = $this->appsecret;
        $param['code'] = $code;
        $param['grant_type'] = 'authorization_code';

        $access_token_url = $this->create_url($url, $param);
        $data = $this->http_get($access_token_url);

        return $this->return_data($data);
    }
896007
function authorizationCodeGrant (code, done) {
  var endpoint = this.endpoints.token
  var provider = this.provider
  var client = this.client
  var url = endpoint.url
  var method = endpoint.method && endpoint.method.toLowerCase()
  var auth = endpoint.auth
  var parser = endpoint.parser
  var accept = endpoint.accept || 'application/json'
  var params = {}

  // required token parameters
  params.grant_type = 'authorization_code'
  params.code = code
  params.redirect_uri = provider.redirect_uri

  // start building the request
  var req = request[method || 'post'](url)

  // Authenticate the client with HTTP Basic
  if (auth === 'client_secret_basic') {
    req.set('Authorization', 'Basic ' + this.base64credentials())
  }

  // Authenticate the client with POST params
  if (auth === 'client_secret_post') {
    params.client_id = client.client_id
    params.client_secret = client.client_secret
  }

  // Add request body params and set other headers
  req.send(qs.stringify(params))
  req.set('accept', accept)
  req.set('user-agent', agent)

  // Execute the request
  return req.end(function (err, res) {
    if (err) { return done(err) }
    var response = (parser === 'x-www-form-urlencoded')
      ? qs.parse(res.text)
      : res.body

    if (res.statusCode !== 200) {
      return done(response)
    }

    done(null, response)
  })
}
1255889
@NotNull
    @ObjectiveCName("validateCodeCommand:")
    public Command<AuthState> validateCode(final String code) {
        return modules.getAuthModule().requestValidateCode(code);
    }
943133
def get_token(code, token_service, client_id, client_secret, redirect_uri,
              grant_type):
  """"""
  data = {
      'code': code,
      'client_id': client_id,
      'client_secret': client_secret,
      'redirect_uri': redirect_uri,
      'grant_type': grant_type,
  }
  # Get the default http client
  resp = requests.post(token_service, data, verify=False)
  return resp.json()
988651
public function getOAuthToken($code)
    {
        // Build data array
        $data = array(
            "grant_type"    => "authorization_code",
            "client_id"     => $this->client_id,
            "client_secret" => $this->client_secret,
            "code"          => $code
        );

        // Perform post request
        $response = $this->request->post("oauth/token", $data);

        return $response;
    }
724806
def fetch_access_token(self, code):
        
        res = self._get(
            'sns/oauth2/access_token',
            params={
                'appid': self.app_id,
                'secret': self.secret,
                'code': code,
                'grant_type': 'authorization_code'
            }
        )
        self.access_token = res['access_token']
        self.open_id = res['openid']
        self.refresh_token = res['refresh_token']
        self.expires_in = res['expires_in']
        return res
306755
@Override
    public WxResp card_code_get(String code, String cardId, Boolean checkConsume) {
    	NutMap body = NutMap.NEW().addv("code", code);
    	if (cardId != null) {
    		body.addv("card_id", cardId);
    	}
    	if (checkConsume != null) {
    		body.addv("check_consume", checkConsume);
    	}

    	// 由于查询Code API中没有“/cgi-bin”，所以uri不能只写“/card/code/get”
    	return postJson("https://api.weixin.qq.com/card/code/get", body);
    }
940417
public Credential authenticate(String authorizationCode, String userId) throws AuthException {
        Preconditions.checkNotNull(authorizationCode, "Authorization code must not be null");
        AuthorizationCodeTokenRequest tokenRequest = authorizationCodeFlow.newTokenRequest(authorizationCode);

        TokenResponse tokenResponse;
        try {
            tokenResponse = tokenRequest
                    .setRedirectUri(redirectUri)
                    .setScopes(scopes)
                    .execute();
        } catch (IOException e) {
            throw new AuthException("Unable to request token.", e);
        }
        try {
            return authorizationCodeFlow.createAndStoreCredential(tokenResponse, userId);
        } catch (IOException e) {
            throw new AuthException("Unable to create and store credential.", e);
        }
    }
972823
private String token(final String home, final String code)
        throws IOException {
        final String uri = this.tkhref.toString();
        return new JdkRequest(uri)
            .method("POST")
            .header("Accept", "application/xml")
            .body()
            .formParam("grant_type", "authorization_code")
            .formParam("client_id", this.app)
            .formParam("redirect_uri", home)
            .formParam("client_secret", this.key)
            .formParam(PsLinkedin.CODE, code)
            .back()
            .fetch().as(RestResponse.class)
            .assertStatus(HttpURLConnection.HTTP_OK)
            .as(JsonResponse.class)
            .json().readObject().getString("access_token");
    }
962731
public ProviderAuthenticationResult handleAuthorizationCode(HttpServletRequest req,
            HttpServletResponse res,
            String authzCode,
            String responseState,
            ConvergedClientConfig clientConfig) {

        String clientId = clientConfig.getClientId();
        OidcClientRequest oidcClientRequest = (OidcClientRequest) req.getAttribute(ClientConstants.ATTRIB_OIDC_CLIENT_REQUEST);
        ProviderAuthenticationResult oidcResult = null;
        oidcResult = authenticatorUtil.verifyResponseState(req, res, responseState, clientConfig);
        if (oidcResult != null) {
            return oidcResult; // only if something bad happened, otherwise proceed to exchange auth code for tokens.
        }
        if (!OIDCClientAuthenticatorUtil.checkHttpsRequirement(clientConfig, clientConfig.getTokenEndpointUrl())) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", clientConfig.getTokenEndpointUrl());
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            return oidcResult;
        }
        String redirect_url = authenticatorUtil.setRedirectUrlIfNotDefined(req, clientConfig);
        if (!OIDCClientAuthenticatorUtil.checkHttpsRequirement(clientConfig, redirect_url)) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", redirect_url);
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            return oidcResult;
        }

        SSLSocketFactory sslSocketFactory = null;
        try {
            sslSocketFactory = getSSLSocketFactory(clientConfig.getTokenEndpointUrl(), clientConfig.getSSLConfigurationName(), clientId);
        } catch (SSLException e) {
            Tr.error(tc, "OIDC_CLIENT_HTTPS_WITH_SSLCONTEXT_NULL", new Object[] { e.getMessage() != null ? e.getMessage() : "invalid ssl context", clientConfig.getClientId() });
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }

        // go get the tokens and validate them.
        try {

            String url = clientConfig.getTokenEndpointUrl();
            if (url == null || url.length() == 0) {
                throw new MalformedURLException("MalformedURLException");
            }
            HashMap<String, String> tokens = oidcClientUtil.getTokensFromAuthzCode(url,
                    clientId,
                    clientConfig.getClientSecret(),
                    redirect_url,
                    authzCode,
                    clientConfig.getGrantType(),
                    sslSocketFactory,
                    clientConfig.isHostNameVerificationEnabled(),
                    clientConfig.getTokenEndpointAuthMethod(),
                    OIDCClientAuthenticatorUtil.getResources(clientConfig),
                    clientConfig.getTokenRequestParams(),
                    clientConfig.getUseSystemPropertiesForHttpClientConnections());

            oidcClientRequest.setTokenType(ClientConstants.TYPE_ID_TOKEN);

            // this has a LOT of dependencies.
            oidcResult = jose4jUtil.createResultWithJose4J(responseState, tokens, clientConfig, oidcClientRequest);

            //if tokens were valid, go get the userinfo if configured to do so, and update the authentication result to include it.
            UserInfoHelper uih = new UserInfoHelper(clientConfig);
            if (uih.willRetrieveUserInfo()) {
                OidcTokenImplBase idToken = null;
                if (oidcResult.getCustomProperties() != null) {
                    idToken = (OidcTokenImplBase) oidcResult.getCustomProperties().get(Constants.ID_TOKEN_OBJECT);
                }
                String subjFromIdToken = null;
                if (idToken != null) {
                    subjFromIdToken = idToken.getSubject();
                }
                if (subjFromIdToken != null) {
                    uih.getUserInfo(oidcResult, sslSocketFactory, tokens.get(Constants.ACCESS_TOKEN), subjFromIdToken);
                }
            }

        } catch (BadPostRequestException e) {
            Tr.error(tc, "OIDC_CLIENT_TOKEN_REQUEST_FAILURE", new Object[] { e.getErrorMessage(), clientId, clientConfig.getTokenEndpointUrl() });
            sendErrorJSON(res, e.getStatusCode(), "invalid_request", e.getErrorMessage());
            oidcResult = new ProviderAuthenticationResult(AuthResult.FAILURE, e.getStatusCode());
        } catch (Exception e) {
            Tr.error(tc, "OIDC_CLIENT_TOKEN_REQUEST_FAILURE", new Object[] { e.getLocalizedMessage(), clientId, clientConfig.getTokenEndpointUrl() });
            oidcResult = new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }
        return oidcResult;
    }
723577
def get_access_token(self, code):
        """"""
        try:
            self._token = super().fetch_token(
                MINUT_TOKEN_URL,
                client_id=self._client_id,
                client_secret=self._client_secret,
                code=code,
            )
        # except Exception as e:
        except MissingTokenError as error:
            _LOGGER.debug("Token issues: %s", error)
        return self._token
457644
private HashMap<String, String> createTokenRequestParams(String grantCode) {

        HashMap<String, String> params = new HashMap<>();

        params.put("code", grantCode);
        params.put("client_id", preferences.clientId.get());
        params.put("grant_type", "authorization_code");
        params.put("redirect_uri", HTTP_LOCALHOST);

        return params;
    }