首页 > 解决方案 > 尝试将数据发布到 Google 工作表时 OAuth 2 身份验证失败

问题描述

我在一个 Gatsby/React 项目上工作,我被要求创建一个表单,可以将数据发布到我们的一个 Google 工作表中。

我已经完成了我能找到的步骤,比如让 Gatsby 将以下内容注入<head>

<script src="https://apis.google.com/js/platform.js" async defer></script>
<meta name="google-signin-client_id" content="<my client ID>.apps.googleusercontent.com">

我创建了工作表,启用了 Google 工作表 API,然后通过 Google 云开发者控制台创建了 API_key 和 CLIENT_ID(OAuth 令牌)。按照 Google自己的示例,我在我的应用程序中进行了设置。

这就是我的页面组件的样子

注意:我在表单中使用 Formik,表单本身没有任何问题。

const Page: FunctionComponent = () => {
  const SHEET_ID = '***;
  const API_KEY = '***';
  const CLIENT_ID = '***';
  const SCOPE = 'https://www.googleapis.com/auth/spreadsheets';
  const formik = useFormik({
    initialValues: {
      field1: '',
      field2: '',
      field3: '',
      field4: ''
    },
    onSubmit: (values) => {
      const params = {
        spreadsheetId: SHEET_ID,
        range: 'Sheet_1',
        valueInputOption: 'RAW',
        dataInsertOption: 'INSERT_ROWS'
      };

      const valueRangeBody = {
        majorDimension: 'ROWS',
        values: [values]
      };

      var request = gapi.client.sheets.spreadsheets.values.append(params, valueRangeBody);
      request.then(function(response) {
        console.log('results', response.result);
      }, function(reason) {
        console.error('error: ' + reason.result.error.message);
      });

    validationSchema: DanceClassesSchema
  });

  const initClient = () => {
    window.gapi.client.init({
      'apiKey': API_KEY,
      'clientId': CLIENT_ID,
      'scope': SCOPE,
      'discoveryDocs': ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
    }).then(function() {
      console.log('initialized');
    }).catch((err) => console.error(err));
  };

  const handleClientLoad = () => {
    window.gapi.load('client:auth2', initClient);
  };

  React.useEffect(() => {
    handleClientLoad();
  }, []);

  return (
    <DefaultLayout>
      <Seo title='' description='' image='' url='' meta={[{ name: 'google-signin-client_id', content: `${CLIENT_ID}.apps.googleusercontent.com` }]} />
          <Form onSubmit={formik.handleSubmit}>

            <Form.Group>
              <Form.Label>
                Lead Name<sup>*</sup>
              </Form.Label>
              <Form.Control
                type='text'
                id='field1'
                name='field1'
                value={formik.values.field1}
                onChange={formik.handleChange}
              />
              {formik.touched.field1 && formik.errors.field1 ? (
                <ErrorMessage>{formik.errors.field1}</ErrorMessage>
              ) : null}
            </Form.Group>

           { /* The other fields are the same  /* }

            <Button variant='primary' type='submit' block>
              Submit
            </Button>
          </Form>
    </DefaultLayout>
  );
};

在提交时,我的表单值与我期望的一样,是一个以它们的名称作为键和表单值的对象。

gapi也可以从代码中访问(我可以将其注销并查看它的所有方法等)。

当页面加载时,我可以看到initialized没有任何错误的日志。当我填写表格并提交时,它会出现以下错误:

error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.

我从 OAuth 提供了正确的 CLIENT_ID,我对此进行了三次检查。错误消息中提供的链接只是告诉我将meta标签注入scripthead我已经完成的地方。

我不确定为什么它仍然说我没有经过身份验证。我通过 Stack Overflow 和 Google 进行的搜索除了可能是范围问题之外没有给我太多帮助,但我已经https://www.googleapis.com/auth/spreadsheets在我的代码和云控制台中设置了范围以获得 OAuth 同意。另一个答案提到了discoveryDocs但它们存在,就像谷歌的例子一样。

我希望这是我在这里所做的显而易见的事情,并感谢任何帮助。

标签: reactjsgoogle-sheetsgoogle-api

解决方案


推荐阅读