automica's avatar
Level 54

Best approach to connect to Etsy API using OAUTH

I'm building out some functionality to allow me to connect with an Etsy store to allow us to get inventory records and to create products.

I've already managed to access some of the read functionality using token authentication, but I'm getting bogged down trying the oauth2 workflow.

I have seen several packages around including a socialite, and passport but would like some clarification on best approach.

I understand that Socialite is to be used to use an external service's user credentials to create a user on my side, essentially for single-sign-on.

Passport appears to be used to allow external users to connect to my service eg oauth flow but with me being the user management and for issuing keys etc.

My use-case is just to

  • authenticate
  • use an authenticated user to access the data I need on the etsy side.

Can someone recommend my best approach for doing this?

i understand i need:

  1. generate a challenge code
  public function generateChallengeCode() {
    // Create a random string.
    $string = $this->createNonce(32);
    // Base64 encode the string.
    $verifier = $this->base64Encode(
      pack("H*", $string)
    );
    // Create a SHA256 hash and base64 encode the string again.
    $code_challenge = $this->base64Encode(
      pack("H*", hash("sha256", $verifier))
    );
    return [$verifier, $code_challenge];
  }
  1. get a authorisation url
  public function getAuthorizationUrl(
    string $redirect_uri,
    array $scope,
    $code_challenge,
    $nonce
  ) {
    $params = [
      "response_type" => "code",
      "redirect_uri" => $redirect_uri,
      "scope" => PermissionScopes::prepare($scope),
      "client_id" => $this->client_id,
      "state" => $nonce,
      "code_challenge" => $code_challenge,
      "code_challenge_method" => "S256"
    ];
    return self::CONNECT_URL."/?".RequestUtil::prepareParameters($params);
  }
  1. use this directly in a browser, to authenticate and then this will redirect me back to my site with a code

  2. i then pass this code with $verifier off to etsy again

  public function requestAccessToken(
    $redirect_uri,
    $code,
    $verifier
  ) {
    $params = [
      "grant_type" => "authorization_code",
      "client_id" => $this->client_id,
      "redirect_uri" => $redirect_uri,
      'code' => $code,
      'code_verifier' => $verifier
    ];
    // Create a GuzzleHttp client.
    $client = $this->createHttpClient();
    try {
      $response = $client->post(self::TOKEN_URL, ['form_params' => $params]);
      $response = json_decode($response->getBody(), false);
      return [
        'access_token' => $response->access_token,
        'refresh_token' => $response->refresh_token
      ];
    }
    catch(\Exception $e) {
      $this->handleAcessTokenError($e);
    }
  }

which gives me [$accessToken, $refreshToken]

part 3 is the bit i'm having an issue with. How would I do this without pasting code into a browser? I want to do this with a console command so won't have the means to paste it into a browser very easily.

Suggestions gratefully received

I'm using https://github.com/rhysnhall/etsy-php-sdk

0 likes
2 replies
LaryAI's avatar
Level 58

To connect to the Etsy API using OAuth2 without manually pasting URLs into a browser, you can automate the process using a headless browser or a service that can handle the OAuth2 flow programmatically. Here’s a step-by-step approach to achieve this:

Step 1: Set Up a Local Web Server

Since OAuth2 requires a redirect URI, you need a local server to handle the redirect and capture the authorization code. You can use PHP’s built-in server or a tool like ngrok to expose your local server to the internet.

Step 2: Automate the Authorization Code Retrieval

You can use a headless browser like Puppeteer (Node.js) or Selenium (available in multiple languages) to automate the login and authorization process. This will simulate a user logging in and authorizing your application.

Step 3: Implement the OAuth2 Flow

  1. Generate the Challenge Code: You already have this part implemented. Ensure your generateChallengeCode function is working correctly.

  2. Get the Authorization URL: Use your getAuthorizationUrl function to generate the URL.

  3. Automate the Authorization: Use a headless browser to navigate to the authorization URL, log in, and authorize the application. Capture the redirect URL to extract the authorization code.

  4. Exchange the Authorization Code for Tokens: Use your requestAccessToken function to exchange the authorization code for access and refresh tokens.

Example Using Puppeteer (Node.js)

Here’s a basic example using Puppeteer to automate the login process:

Step 4: Use the Authorization Code

Once you have the authorization code, you can use your requestAccessToken function to obtain the access and refresh tokens.

Considerations

  • Security: Ensure that your credentials are stored securely and not hardcoded in your scripts.
  • Error Handling: Implement robust error handling to manage failed logins or authorization errors.
  • Environment: Ensure your environment can run Node.js and Puppeteer or any other automation tool you choose.

By automating the OAuth2 flow, you can handle the entire process programmatically, which is especially useful for console applications or server-side scripts.

martinbean's avatar

@automica Use Socialite to get OAuth tokens from other providers (i.e. Etsy). Use Passport to offer tokens to other parties, to allow them your users to authorize access to those providers.

So yes, in your case you would want to use Socialite to obtain an access token for an Etsy user. You can use this: https://socialiteproviders.com/Etsy

Once you have an OAuth token for an Etsy user, you will be able to make requests to Etsy’s API as that user.

1 like

Please or to participate in this conversation.