Module: ShopifyAPI::Auth::RefreshToken

Extended by:
T::Sig
Defined in:
lib/shopify_api/auth/refresh_token.rb

Class Method Summary collapse

Class Method Details

.refresh_access_token(shop:, refresh_token:) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/shopify_api/auth/refresh_token.rb', line 18

def refresh_access_token(shop:, refresh_token:)
  unless ShopifyAPI::Context.setup?
    raise ShopifyAPI::Errors::ContextNotSetupError,
      "ShopifyAPI::Context not setup, please call ShopifyAPI::Context.setup"
  end

  shop_session = ShopifyAPI::Auth::Session.new(shop:)
  body = {
    client_id: ShopifyAPI::Context.api_key,
    client_secret: ShopifyAPI::Context.api_secret_key,
    grant_type: "refresh_token",
    refresh_token:,
  }

  client = Clients::HttpClient.new(session: shop_session, base_path: "/admin/oauth")
  response = begin
    client.request(
      Clients::HttpRequest.new(
        http_method: :post,
        path: "access_token",
        body:,
        body_type: "application/json",
      ),
    )
  rescue ShopifyAPI::Errors::HttpResponseError => error
    ShopifyAPI::Context.logger.debug("Failed to refresh access token: #{error.message}")
    raise error
  end

  session_params = T.cast(response.body, T::Hash[String, T.untyped]).to_h

  Session.from(
    shop:,
    access_token_response: Oauth::AccessTokenResponse.from_hash(session_params),
  )
end