Firebase HTTP 함수 (Firebase, Stripe OAuth, React (JSX) 프런트 엔드)를 사용하여 Stripe에 인증 코드 반환

Aug 20 2020

Stripe OAuth 프로세스를 완료하려는 React 프런트 엔드, Firebase 백 엔드가 있습니다. 리디렉션 URI가 돌아 왔습니다 (https://mywebsitename.com/oauth_return) 및 해당 페이지에서 열어 본 반응 구성 요소는 해당 URL을 구문 분석하고 인증 코드 및 상태에 액세스합니다. (아래를 봐주세요)

"oauth_return.js"파일 내부

import React from 'react';
import queryString from 'query-string';

const oauth_redirect  = () => {

    //Parsing over URL
    const value=queryString.parse(window.location.search);
    const code=value.code;
    console.log('code:', code)
    const state=value.state;
    console.log('state:', state)
}
export default (oauth_redirect)

내가하는 데 어려움이있는 것은 firebase HTTP 함수가 POST 메소드를 통해 인증 코드를 반환하도록 만드는 방법을 알아내는 것입니다. 모든 Firebase 함수는 functions 디렉토리의 "index.js"파일에 있습니다. 내가 본 모든 튜토리얼은 Typescript에서이 함수를 빌드하는 다양한 방법을 보여 주지만, 내 코드는 Javascript로 작성되어야합니다.

"functions / index.js"파일 내부

(...)

  exports.stripeCreateOathResponseToken = functions.https.onRequest((req, res) => {

  (...) Not sure what to write in this function to return the authorization code. All tutorials I've found are written in Typescript.

});

불행히도이 HTTP 함수가 처음에 호출되도록 트리거되는 방법을 이해하지 못합니다 (즉, "oauth_return.js"파일 내에서 명시 적으로 호출해야합니까? 인증 코드를 어떻게 전달합니까? 그리고 대부분 중요한 것은 인증 코드를 어떻게 Stripe로 되돌려 보내는가?

이 문제에 대한 명확한 설명을 주시면 감사하겠습니다.

답변

2 RameshD Aug 20 2020 at 16:30

다음은 정확한 용도로 작성된 작업 코드입니다. 이것이 해결책을 제공하는 데 도움이되기를 바랍니다.

exports.stripeCreateOathResponseToken = functions.https.onRequest((req, res) => {

    res.set('Access-Control-Allow-Origin', '*');

    if (req.method === 'OPTIONS') {
        console.log('Executing OPTIONS request code block');
        res.set('Access-Control-Allow-Methods', 'POST');
        res.set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept');
        res.set('Access-Control-Max-Age', '3600');
        res.status(204).send('');
    } else if (req.method === 'POST') {
        console.log('Executing POST request code block');
        return oauthResponseCheck(req, res);
    }
    else {
        // Log, but ignore requests which are not OPTIONS or POST.
        console.log(`We received an invalid request method of type: ${req.method}`);
        return;
    }
});


function oauthResponseCheck(req, res) {
     // code: An authorization code you can use in the next call to get an access token for your user.
    // This can only be used once and expires in 5 minutes.

    // state: The value of the state parameter you provided on the initial POST request.
    const { code, state } = req.body;

    // Assert the state matches the state you provided in the OAuth link (optional).
    if (!stateMatches(state)) {
        console.log('Incorrect state parameter for state::', state)
        return res.status(403).json({ error: 'Incorrect state parameter: ' + state });
    }
   
    // Send the authorization code to Stripe's API.
    stripe.oauth.token({
        grant_type: 'authorization_code',
        code
    }).then(
        (response) => {
            var stripe_connected_account_id = response.stripe_user_id;
         
            console.log('Stripe Connected Account Saved successfully: ' + JSON.stringify(response));
            return res.status(200).json({
                status: true,
                message: 'Stripe Connected Account Saved successfully',
                data: response
            });

        },
        (err) => {
            if (err.type === 'StripeInvalidGrantError') {
                console.log('Invalid authorization code: ' + code);
                return res.status(400).json({
                    status: false,
                    message: 'Invalid authorization code.::' + code,
                }
                );
            } else {
                console.log('An unknown error occurred: ' + err);
                return res.status(500).json({
                    status: false,
                    message: 'An unknown error occurred.::' + err,
                });
            }
        }
    );
})