方形连接表格重定向付款表格

时间:2019-10-21 21:54:58

标签: square-connect

我正在尝试使用方形身份验证表单来连接我的Web应用程序上的服务提供商,但在本地开发环境中却始终收到404。我正在尝试连接我的第一个商家帐户。

我的问题是为什么重定向URL不起作用。我相信它是https://connect.squareup.com/oauth2 /授权

,但是它不起作用。我已设置的所有其他内容以及应用程序仪表板显示我有1个活动令牌。我不知道那是什么意思我需要商家或服务提供商通过我的Web应用程序进行连接并授权我的应用程序代表他们收费。我不确定是否需要在授权或代码方面做任何其他事情。

这是反应重定向页面

import React, { Component } from 'react';
// import axios from 'axios';
import qs from 'query-string';
import {
  API, graphqlOperation, Auth,
} from 'aws-amplify';
import { Dimmer, Loader, Message } from 'semantic-ui-react';
import axios from 'axios';
import GetProviderMerchantId from '../../GraphQL/Payment/GetProviderMerchantId';
import RemoveProviderPaymentSetup from '../../GraphQL/Payment/RemoveProviderPaymentSetup';
//  import RemoveProviderTablePaymentDetails from '../../GraphQL/RemoveProviderTablePaymentDetails';
// import StripeButton from '../../../public/stripe-button.png';

const SQUARECONNECTURL = process.env.REACT_APP_SQUARE_CONNECT;
const DEAUTHORIZESQUAREURL = process.env.REACT_APP_SQUARE_DEAUTH;
const CLIENTID = 'sq0idp---xxxxxxxxxxxxxxxxx';
//  const TESTCLIENTID = 'ca_xxxxxxxxxxxxxxxxxxx';

class ProviderStartSquare extends Component {
  constructor(props) {
    super(props);
    this.state = {
      stringifiedURL: null,
      merchantId: null,
      jwtToken: null,
      providerId: null,
      isLoading: true,
    };
  }

  async componentDidMount() {
    try {
      const user = await Auth.currentAuthenticatedUser();
      console.log('current authenticated user', user);
      const session = await Auth.currentSession();
      const { idToken } = session;
      console.log('this is the idtoken', idToken);
      const { payload, jwtToken } = idToken;

      this.setState({ jwtToken });
      this.setState({ providerId: payload.sub });

      console.log(CLIENTID, payload.sub);

      const url = SQUARECONNECTURL;
      const params = {
        client_id: CLIENTID,
        state: payload.sub,
        scope: `PAYMENTS_WRITE PAYMENTS_READ
          PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS CUSTOMERS_READ
          CUSTOMERS_WRITE MERCHANT_PROFILE_READ`,
      };
        //  const config = {
        //  params,
      /*
          headers: {
            Authorization: `Basic ${ENCODEDSERVERSECRET}`,
            'Content-Type': 'application/json',
          },        */
      //  };
      //  await axios.get(url, config);
      //  response will include code, scope, state
      // code is authorization code, valid for 5 Minutes
      // it will be inside the Destinationstripe
      const stringified = qs.stringify(params, { arrayFormat: 'bracket' });


      this.setState({ stringifiedURL: `${url}?${stringified}` });

      //  get the PaymentSetup and from there merchantId
      const parameters = {
        ProviderId: payload.sub,
      };
      const providerPaymentSetupData = await API
        .graphql(
          graphqlOperation(
            GetProviderMerchantId, parameters,
          ),
        );
      const {
        data: {
          getProviderProfile: {
            PaymentSetup: paymentSetup,
          },
        },
      } = providerPaymentSetupData;
      if (paymentSetup && paymentSetup.MerchantId) {
        const { MerchantId } = paymentSetup;
        this.setState({ merchantId: MerchantId });
      }
      this.setState({ isLoading: false });
    } catch (e) {
      console.error(e, ' this is error inside componentDidMount of EntProviderStartSquare');
      this.setState({ isLoading: false });
    }
  }

  deauthorizeStripe = async (merchantId) => {
    try {
      const url = DEAUTHORIZESQUAREURL;
      /*
      const bodyFormData = new FormData();
      bodyFormData.set('client_id', TESTCLIENTID);
      bodyFormData.set('stripe_user_id', merchantId);
      const data = bodyFormData;      */

      const { providerId } = this.state;


      if (!providerId) {
        return this.setState({
          error: 'Please login again before proceeding further',
          success: null,
        });
      }

      const data = JSON.stringify({
        merchantId,
      });


      const { jwtToken } = this.state;
      const config = {
        headers: {
          Authorization: jwtToken,
          'Content-Type': 'application/json',
        },
      };


      const res = await axios.post(url, data, config);
      if (res.status === 200 || res.status === 401) {
        // remove from our servers
        const parameters = {
          input: {
            PaymentSetup: {
              MerchantId: null,
              AccessToken: null,
              ExpiresAt: null,
              RefreshToken: null,
            },
          },
        };

        const removeProviderPaymentSetupData = await API
          .graphql(
            graphqlOperation(
              RemoveProviderPaymentSetup, parameters,
            ),
          );
        const {
          data: {
            updateProviderProfile: {
              ProviderId: deletedProviderId,
              PaymentSetup: {
                MerchantId: deleteMerchantId,
                AccessToken: deleteAccessToken,
                RefreshToken: deleteRefreshToken,
              },
            },
          },
        } = removeProviderPaymentSetupData;
        console.log(deletedProviderId, deleteMerchantId, deleteAccessToken,
          deleteRefreshToken, ' these were deleted');
        /*
        //   remove from providerTablePaymentDetails
        const parameters2 = {
          UpdateProvidersInput: {
            Provider_id: providerId,
            PaymentSetup: null,
          },
        };

        const removeProviderTablePaymentDetailsData = await API
          .graphql(
            graphqlOperation(
              RemoveProviderTablePaymentDetails, parameters2,
            ),
          );
        const {
          data: {
            updateProviders: {
              Provider_id: deletedProviderId2, PaymentSetup: deletedPaymentSetup,
            },
          },
        } = removeProviderTablePaymentDetailsData;
        console.log(deletedProviderId2,
        deletedPaymentSetup, ' updated provider table with payment details');
        */
        this.setState({ success: 'Deauthorization successful!', error: null, merchantId: null });
      }
    } catch (e) {
      console.error(e, ' unable to deauthorize stripe.');
      this.setState({ error: e.message, success: null });
    }
  }

  render() {
    const {
      stringifiedURL, merchantId, isLoading,
      success, error,
    } = this.state;
    return (
      <div>
        {isLoading
          ? (
            <Loader active>
              <Dimmer />
            </Loader>
          )
          : (
            <div className="w-100 vh-100">
              <div className="mw6 center">
                {success && (
                  <Message
                    success
                    header="Success!"
                    content={success}
                  />
                )}
                {error && (
                  <Message
                    error
                    header="There was some errors with your submission"
                    list={[
                      error,
                    ]}
                  />
                )}
              </div>
              {merchantId && (
                <div>
                  <p className="f5 fw5 ma3">
                    Your account is successfully authorized to accept payments!
                  </p>
                  <button
                    type="button"
                    className="b blue br2 ph3 pv2 ba b--blue bg-transparent grow pointer f6 dib"
                    onClick={() => this.deauthorizeStripe(merchantId)}
                  >
                    Deauthorize Square
                  </button>
                </div>
              )}
              {!merchantId && (
                <div className="dt vh-50-ns pa2 w-100-ns">
                  <div className="dtc v-mid">
                    <button onClick={() => window.open(stringifiedURL, '_blank')} className="br3 f3-ns fw3 f4 b link pointer grow dim b--none bg-orange white pv2" type="button">
                      Authorize this application
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}
      </div>
    );
  }
}

export default ProviderStartSquare;

0 个答案:

没有答案