第二步:处理回调并获取access_token。与getAccessToken不同的是会验证state值是否匹配，防止csrf攻击。
@param string $storeState 存储的正确的state
@param string $code 第一步里$redirectUri地址中传过来的code，为null则通过get参数获取
@param string $state 回调接收到的state，为null则通过get参数获取
@return string
557314
protected function __getAccessToken($storeState, $code = null, $state = null)
	{
		$this->result = $this->http->post($this->getUrl('oauth2/access_token'), array(
			'client_id'		=>	$this->appid,
			'client_secret'	=>	$this->appSecret,
			'grant_type'	=>	'authorization_code',
			'code'			=>	isset($code) ? $code : (isset($_GET['code']) ? $_GET['code'] : ''),
			'redirect_uri'	=>	$this->getRedirectUri(),
		))->json(true);
		if(isset($this->result['error_code']))
		{
			throw new ApiException($this->result['error'], $this->result['error_code']);
		}
		else
		{
			$this->openid = $this->result['uid'];
			return $this->accessToken = $this->result['access_token'];
		}
	}
270471
public function getAccessToken($code = '')
	{
		$dta = array('client_id' => $this->_API['API_KEY'], 'client_secret' => $this->_API['API_SECRET'], 'code' => $code);
		$data = $this->call(['METHOD' => 'POST', 'URL' => 'https://' . $this->_API['SHOP_DOMAIN'] . '/admin/oauth/access_token', 'DATA' => $dta], FALSE);

		return $data->access_token;
	}
1316540
public function fetchAccessToken($redirect_code)
    {
        $http = $this->getHTTPClient();
        $post_data = [
            'client_id' => $this->client_id,
            'client_secret' => $this->client_secret,
            'grant_type' => 'authorization_code',
            'code' => $redirect_code,
            'redirect_uri' => $this->getRedirectURL(),
        ];
        // Request access token
        try {
            $response = $http->request('POST', 'oauth/access_token', [
                'form_params' => $post_data
            ]);

            $responseBody = $response->getBody();
            $responseArr = json_decode($responseBody, true);

            //Set new data into the config and update the current instance
            $this->setAccessToken($responseArr['access_token']);
            $this->setAccessTokenExpire($responseArr['expires_in']);
            $this->setRefreshToken($responseArr['refresh_token']);
        } catch (\Exception  $exception) {
            $this->handleException($exception);
        }
    }
636656
public AccessToken obtainAccessTokenByCode(String authorizationCode) throws InvalidCodeException, TokenExpiredException {
        AccessToken token = tp().obtainAccessTokenByAuthzCode(authorizationCode);
        return token;
    }
530213
public function getAccessToken($code, $grant = 'authorization_code')
    {
        $this->validateCsrf();
        return $this->provider->getAccessToken($grant, ['code' => $code]);
    }
291678
public String getOauthPageUrl(String redirectUrl, OauthScope scope, String state){
        if(StrUtil.isBlank(redirectUrl)){
            throw new NullPointerException("redirectUrl is null");
        }
        BeanUtil.requireNonNull(scope, "scope is null");
        String userstate = StrUtil.isBlank(state) ? "STATE" : state;
        String url = null;
        try{
            url = URLEncoder.encode(redirectUrl, "UTF-8");
        }catch (UnsupportedEncodingException e){
            LOG.error("异常", e);
        }
        StringBuffer stringBuffer = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize?");
        stringBuffer.append("appid=").append(this.config.getCorpid())
                .append("&redirect_uri=").append(url)
                .append("&response_type=code&scope=").append(scope.toString())
                .append("&state=").append(userstate)
                .append("#wechat_redirect");
        return stringBuffer.toString();
    }
857227
public function getAccessToken($code, $state = null, $redirectUri = null)
    {
        // No state provided
        // Should probably be
        // handled explicitly
        if (!is_null($state)) {
            //Decode the State
            $state = $this->decodeState($state);

            //CSRF Token
            $csrfToken = $state['csrfToken'];

            //Set the URL State
            $this->urlState = $state['urlState'];

            //Validate CSRF Token
            $this->validateCSRFToken($csrfToken);
        }

        //Fetch Access Token
        $accessToken = $this->getOAuth2Client()->getAccessToken($code, $redirectUri);

        //Make and return the model
        return new AccessToken($accessToken);
    }
524197
public function getOauth2AccessToken($code, $grantType = 'authorization_code')
    {
        $result = $this->httpGet(self::WECHAT_OAUTH2_ACCESS_TOKEN_PREFIX, [
            'appid' => $this->appId,
            'secret' => $this->appSecret,
            'code' => $code,
            'grant_type' => $grantType
        ]);
        return !array_key_exists('errcode', $result) ? $result : false;
    }
111234
public function getAuthorizeUserInfo($state = 'authorize', $scope = 'snsapi_base')
    {
        $request = Yii::$app->request;
        if (($code = $request->get('code')) && $request->get('state') == $state) {
            return $this->getOauth2AccessToken($code);
        } else {
            Yii::$app->getResponse()->redirect($this->getOauth2AuthorizeUrl($request->getAbsoluteUrl(), $state, $scope));
            Yii::$app->end();
        }
    }
1185237
public void getUserCredentials( String codeOrUrl )
            throws IOException
    {
        if ( state == null ) {
            // should not occur if this class is used properly
            throw new IllegalStateException( "No anti CSRF state defined" );
        }

        String code;
        if ( codeOrUrl.startsWith( "http://" ) || codeOrUrl.startsWith( "https://" ) ) {
            // It's a URL : extract code and check state
            String url = codeOrUrl;

            LOGGER.debug( "redirect URL: {}", url );

            URI uri = URI.create( url );
            String error = URIUtil.getQueryParameter( uri, "error" );
            String errorDescription = URIUtil.getQueryParameter( uri, "error_description" );
            if ( error != null ) {
                String msg = "User authorization failed : " + error;
                if ( errorDescription != null ) {
                    msg += " (" + errorDescription + ")";
                }
                throw new CStorageException( msg );
            }

            String stateToTest = URIUtil.getQueryParameter( uri, "state" );
            if ( !state.equals( stateToTest ) ) {
                throw new CStorageException( "State received (" + stateToTest + ") is not state expected (" + state + ")" );
            }
            code = URIUtil.getQueryParameter( uri, "code" );
            if ( code == null ) {
                throw new CStorageException( "Can't find code in redirected URL: " + url );
            }

        } else {
            // It's a code
            code = codeOrUrl;
        }

        UserCredentials userCredentials = sessionManager.fetchUserCredentials( code );
        // From access token we can get user id...
        String userId = storageProvider.getUserId();
        LOGGER.debug( "User identifier retrieved: {}", userId );

        // ...so that by now we can persist tokens :
        userCredentials.setUserId( userId );
        sessionManager.getUserCredentialsRepository().save( userCredentials );
    }
676978
def get_access_token(self, code):
        

        payload = {'redirect_uri': self.redirect_uri,
                   'code': code,
                   'grant_type': 'authorization_code'}

        headers = self._make_authorization_headers()

        response = requests.post(self.OAUTH_TOKEN_URL, data=payload,
            headers=headers, verify=LOGIN_VERIFY_SSL_CERT)
        if response.status_code is not 200:
            raise MercedesMeAuthError(response.reason)
        token_info = response.json()
        token_info = self._add_custom_values_to_token_info(token_info)
        self._save_token_info(token_info)
        return token_info
1268207
public function getAuthenticationUrl($state = null, $forceVerify = false)
    {
        return implode('', [
            sprintf('%soauth2/authorize', $this->baseUri),
            '?response_type=code',
            sprintf('&client_id=%s', $this->getClientId()),
            sprintf('&redirect_uri=%s', $this->getRedirectUri()),
            sprintf('&scope=%s', implode('+', $this->getScope())),
            sprintf('&state=%s', $state),
            sprintf('&force_verify=%s', $forceVerify ? 'true' : 'false'),
        ]);
    }
463475
public String getRedirectUri(AccessTokenRequest request) {

		String redirectUri = request.getFirst("redirect_uri");

		if (redirectUri == null && request.getCurrentUri() != null && useCurrentUri) {
			redirectUri = request.getCurrentUri();
		}

		if (redirectUri == null && getPreEstablishedRedirectUri() != null) {
			// Override the redirect_uri if it is pre-registered
			redirectUri = getPreEstablishedRedirectUri();
		}

		return redirectUri;

	}
131491
public function getAccessToken($code, $redirectUri = null, $grant_type = 'authorization_code')
    {
        //Request Params
        $params = [
        'code' => $code,
        'grant_type' => $grant_type,
        'client_id' => $this->getApp()->getClientId(),
        'client_secret' => $this->getApp()->getClientSecret(),
        'redirect_uri' => $redirectUri
        ];

        $params = http_build_query($params);

        $apiUrl = static::AUTH_TOKEN_URL;
        $uri = $apiUrl . "?" . $params;

        //Send Request through the DropboxClient
        //Fetch the Response (DropboxRawResponse)
        $response = $this->getClient()
        ->getHttpClient()
        ->send($uri, "POST", null);

        //Fetch Response Body
        $body = $response->getBody();

        //Decode the Response body to associative array
        //and return
        return json_decode((string) $body, true);
    }
791703
public function requestAccessToken($callbackUri, $authorizationCode)
    {
        $params = array(
            'client_id' => $this->appId,
            'client_secret' => $this->appSecret,
            'code' => $authorizationCode,
            'grant_type' => 'authorization_code',
            'redirect_uri' => $callbackUri,
            'response_type' => 'code',
            'scope' => $this->scope,
            'strict' => $this->strictChecks,
        );

        $url = sprintf('%s%s', $this->endpoint, $this->paths['access_token']);

        $this->logger->info(sprintf("Requesting AccessToken to '%s'", $url));
        $this->logger->debug(sprintf('Sent params: %s', json_encode($params)));

        $response = $this->browser->submit($url, $params);

        $this->logger->debug(sprintf('Response of AccessToken: %s', $response));

        $content = $response->getContent();
        $response = json_decode($content, true);

        if (null === $response) {
            $this->logger->error('Received non-json response.', array('response' => $content));

            throw new OAuthException('provider', "Response content couldn't be converted to JSON.");
        }

        if (isset($response['error'])) {
            $this->logger->error('The OAuth2 provider responded with an error', array('response' => $response));

            $error = $response['error'];
            $message = $response['message'];

            throw new OAuthException($error, $message);
        }

        $token = $response['access_token'];
        $scope = $response['scope'];

        return array('access_token' => $token, 'scope' => $scope);
    }
984391
protected function getTokenUrl($code) {
		return $this->providerOptions['access_token'] . '?client_id=' . $this->client_id . '&client_secret=' . $this->client_secret . '&code=' . $code . '&redirect_uri=' . urlencode($this->getState('redirect_uri'));
	}
677617
public URI getRedirectToFromState(final String state)
	{
		final String[] pieces = decodeState(state).split(" ", 2);

		if (!StringUtils.equals(callbackNonce, pieces[0]))
		{
			// The callback nonce is not what we expect; this is usually caused by:
			// - The user has followed a previous oauth callback entry from their history
			// - The user has accessed a service via a non-canonical endpoint and been redirected by the oauth server to the canonical one
			//   which means the original nonce stored in the session is not available to this session.

			// To get around this, we simply redirect the user to the root of this service so they can start the oauth flow again
			throw new LiteralRestResponseException(Response.seeOther(URI.create("/")).build());
		}

		if (pieces.length == 2)
			return URI.create(pieces[1]);
		else
			return null;
	}