repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/payout_infos_controller.rb | app/controllers/admin/users/payout_infos_controller.rb | # frozen_string_literal: true
class Admin::Users::PayoutInfosController < Admin::Users::BaseController
before_action :fetch_user
def show
render json: @user.payout_info
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/payouts_controller.rb | app/controllers/admin/users/payouts_controller.rb | # frozen_string_literal: true
class Admin::Users::PayoutsController < Admin::BaseController
include Pagy::Backend
before_action :fetch_user, only: [:index, :pause, :resume]
RECORDS_PER_PAGE = 20
private_constant :RECORDS_PER_PAGE
def index
@title = "Payouts"
pagination, @payouts = pagy(
@user.payments.order(id: :desc),
limit: params[:per_page] || RECORDS_PER_PAGE,
page: params[:page]
)
render inertia: "Admin/Users/Payouts/Index",
props: {
payouts: @payouts.includes(:user, bank_account: :credit_card).map { Admin::PaymentPresenter.new(payment: _1).props },
pagination: PagyPresenter.new(pagination).props
}
end
def pause
reason = params.require(:pause_payouts).permit(:reason)[:reason]
@user.update!(payouts_paused_internally: true, payouts_paused_by: current_user.id)
@user.comments.create!(
author_id: current_user.id,
content: reason,
comment_type: Comment::COMMENT_TYPE_PAYOUTS_PAUSED
) if reason.present?
render json: { success: true, message: "User's payouts paused" }
end
def resume
render json: { success: false } and return unless @user.payouts_paused_internally?
@user.update!(payouts_paused_internally: false, payouts_paused_by: nil)
@user.comments.create!(
author_id: current_user.id,
content: "Payouts resumed.",
comment_type: Comment::COMMENT_TYPE_PAYOUTS_RESUMED
)
render json: { success: true, message: "User's payouts resumed" }
end
private
def fetch_user
@user = User.find_by(id: params[:user_id]) || e404
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/latest_posts_controller.rb | app/controllers/admin/users/latest_posts_controller.rb | # frozen_string_literal: true
class Admin::Users::LatestPostsController < Admin::Users::BaseController
before_action :fetch_user
def index
render json: @user.last_5_created_posts
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/products/tos_violation_flags_controller.rb | app/controllers/admin/users/products/tos_violation_flags_controller.rb | # frozen_string_literal: true
class Admin::Users::Products::TosViolationFlagsController < Admin::Users::Products::BaseController
def index
if @user.flagged_for_tos_violation?
render json: {
tos_violation_flags: @product.comments.with_type_flagged.as_json(
only: %i[id content]
)
}
else
render json: { tos_violation_flags: [] }
end
end
def create
suspend_tos_reason = suspend_tos_params[:reason]
if @user.nil? || suspend_tos_reason.blank?
render json: { success: false, error_message: "Invalid request" }, status: :bad_request
elsif !@user.can_flag_for_tos_violation?
render json: { success: false, error_message: "Cannot flag for TOS violation" }, status: :bad_request
else
ActiveRecord::Base.transaction do
@user.update!(tos_violation_reason: suspend_tos_reason)
comment_content = "Flagged for a policy violation on #{Time.current.to_fs(:formatted_date_full_month)} for a product named '#{@product.name}' (#{suspend_tos_reason})"
@user.flag_for_tos_violation!(author_id: current_user.id, product_id: @product.id, content: comment_content)
@product.public_send(@product.is_tiered_membership? ? :unpublish! : :delete!)
end
render json: { success: true }
end
end
private
def suspend_tos_params
params.require(:suspend_tos).permit(:reason)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/users/products/base_controller.rb | app/controllers/admin/users/products/base_controller.rb | # frozen_string_literal: true
class Admin::Users::Products::BaseController < Admin::Users::BaseController
before_action :fetch_user
before_action :set_product
private
def set_product
@product = Link.find_by_external_id(params[:product_external_id])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/search/purchases_controller.rb | app/controllers/admin/search/purchases_controller.rb | # frozen_string_literal: true
class Admin::Search::PurchasesController < Admin::BaseController
include Pagy::Backend
RECORDS_PER_PAGE = 25
def index
@title = "Purchase results"
search_params = params.permit(:transaction_date, :last_4, :card_type, :price, :expiry_date, :purchase_status).to_hash.symbolize_keys
if search_params[:transaction_date].present?
begin
search_params[:transaction_date] = Date.strptime(search_params[:transaction_date], "%m/%d/%Y").to_s
rescue ArgumentError
flash[:alert] = "Please enter the date using the MM/DD/YYYY format."
search_params.delete(:transaction_date)
end
end
@purchases = AdminSearchService.new.search_purchases(
query: params[:query]&.strip,
product_title_query: params[:product_title_query]&.strip,
**search_params,
)
pagination, purchases = pagy_countless(
@purchases,
limit: params[:per_page] || RECORDS_PER_PAGE,
page: params[:page],
countless_minimal: true
)
return redirect_to admin_purchase_path(purchases.first.external_id) if purchases.one? && pagination.page == 1
purchases = purchases.map do |purchase|
Admin::PurchasePresenter.new(purchase).list_props
end
respond_to do |format|
format.html do
render(
inertia: "Admin/Search/Purchases/Index",
props: { purchases: InertiaRails.merge { purchases }, pagination: },
)
end
format.json { render json: { purchases:, pagination: } }
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/admin/search/users_controller.rb | app/controllers/admin/search/users_controller.rb | # frozen_string_literal: true
class Admin::Search::UsersController < Admin::BaseController
include Admin::ListPaginatedUsers
def index
@title = "Search for #{params[:query].present? ? params[:query].strip : "users"}"
@users = User.admin_search(params[:query]).order(created_at: :desc)
list_paginated_users(users: @users, template: "Admin/Search/Users/Index", legacy_template: "admin/search/users/index", single_result_redirect_path: method(:admin_user_path))
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/help_center/articles_controller.rb | app/controllers/help_center/articles_controller.rb | # frozen_string_literal: true
class HelpCenter::ArticlesController < HelpCenter::BaseController
before_action :redirect_legacy_articles, only: :show
def index
@props = {
categories: HelpCenter::Category.all.map do |category|
{
title: category.title,
url: help_center_category_path(category),
audience: category.audience,
articles: category.articles.map do |article|
{
title: article.title,
url: help_center_article_path(article)
}
end
}
end
}
@title = "Gumroad Help Center"
@canonical_url = help_center_root_url
@description = "Common questions and support documentation"
end
def show
@article = HelpCenter::Article.find_by!(slug: params[:slug])
@title = "#{@article.title} - Gumroad Help Center"
@canonical_url = help_center_article_url(@article)
end
private
LEGACY_ARTICLE_REDIRECTS = {
"284-jobs-at-gumroad" => "/about#jobs"
}
def redirect_legacy_articles
return unless LEGACY_ARTICLE_REDIRECTS.key?(params[:slug])
redirect_to LEGACY_ARTICLE_REDIRECTS[params[:slug]], status: :moved_permanently
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/help_center/categories_controller.rb | app/controllers/help_center/categories_controller.rb | # frozen_string_literal: true
class HelpCenter::CategoriesController < HelpCenter::BaseController
def show
@category = HelpCenter::Category.find_by!(slug: params[:slug])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/help_center/base_controller.rb | app/controllers/help_center/base_controller.rb | # frozen_string_literal: true
class HelpCenter::BaseController < ApplicationController
layout "help_center"
rescue_from ActiveHash::RecordNotFound, with: :redirect_to_help_center_root
private
def redirect_to_help_center_root
redirect_to help_center_root_path, status: :found
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/media_locations_controller.rb | app/controllers/api/mobile/media_locations_controller.rb | # frozen_string_literal: true
class Api::Mobile::MediaLocationsController < Api::Mobile::BaseController
include RecordMediaLocation
before_action { doorkeeper_authorize! :mobile_api }
def create
render json: { success: record_media_location(params) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/subscriptions_controller.rb | app/controllers/api/mobile/subscriptions_controller.rb | # frozen_string_literal: true
class Api::Mobile::SubscriptionsController < Api::Mobile::BaseController
before_action :fetch_subscription_by_external_id, only: :subscription_attributes
def subscription_attributes
render json: { success: true, subscription: @subscription.subscription_mobile_json_data }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/installments_controller.rb | app/controllers/api/mobile/installments_controller.rb | # frozen_string_literal: true
class Api::Mobile::InstallmentsController < Api::Mobile::BaseController
before_action :fetch_installment, only: [:show]
before_action :fetch_context_object, only: [:show]
def show
render json: { success: true, installment: @installment.installment_mobile_json_data(purchase: @purchase,
subscription: @subscription,
imported_customer: @imported_customer,
follower: @follower) }
end
private
def fetch_installment
@installment = Installment.find_by_external_id(params[:id])
render json: { success: false, message: "Could not find installment" }, status: :not_found if @installment.nil?
end
def fetch_context_object
if params[:purchase_id].present?
@purchase = Purchase.find_by_external_id(params[:purchase_id])
elsif params[:subscription_id].present?
@subscription = Subscription.find_by_external_id(params[:subscription_id])
elsif params[:imported_customer_id].present?
@imported_customer = ImportedCustomer.find_by_external_id(params[:imported_customer_id])
elsif params[:follower_id].present?
@follower = Follower.find_by_external_id(params[:follower_id])
else
render json: { success: false, message: "Could not find related object to the installment." }, status: :not_found
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/feature_flags_controller.rb | app/controllers/api/mobile/feature_flags_controller.rb | # frozen_string_literal: true
class Api::Mobile::FeatureFlagsController < Api::Mobile::BaseController
before_action { doorkeeper_authorize! :mobile_api }
def show
render json: { enabled_for_user: Feature.active?(params[:id], current_resource_owner) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/purchases_controller.rb | app/controllers/api/mobile/purchases_controller.rb | # frozen_string_literal: true
class Api::Mobile::PurchasesController < Api::Mobile::BaseController
before_action { doorkeeper_authorize! :mobile_api }
before_action :fetch_purchase, only: [:purchase_attributes, :archive, :unarchive]
DEFAULT_SEARCH_RESULTS_SIZE = 10
def index
purchases = current_resource_owner.purchases.for_mobile_listing
purchases_json = if params[:per_page] && params[:page]
purchases_to_json(
purchases.page_with_kaminari(params[:page]).per(params[:per_page])
)
else
media_locations_scope = MediaLocation.where(product_id: purchases.pluck(:link_id))
cache [purchases, media_locations_scope], expires_in: 10.minutes do
purchases_to_json(purchases)
rescue => e
# Cache empty array for requests that timeout to reduce the load on database.
# TODO: Remove this once we fix the bottleneck with the purchases_json generation
Rails.logger.info "Error generating purchases json for user: #{current_resource_owner.id}, #{e.class} => #{e.message}"
Bugsnag.notify(e)
[]
end
end
render json: { success: true, products: purchases_json, user_id: current_resource_owner.external_id }
end
def search
result = PurchaseSearchService.search(search_options)
pagination = Pagy.new(count: result.response.hits.total.value, page: @page, limit: @items)
render json: {
success: true,
user_id: current_resource_owner.external_id,
purchases: purchases_to_json(result.records),
sellers: formatted_sellers_agg(result.aggregations.seller_ids),
meta: { pagination: PagyPresenter.new(pagination).metadata }
}
end
def purchase_attributes
render json: { success: true, product: @purchase.json_data_for_mobile }
end
def archive
@purchase.is_archived = true
@purchase.save!
render json: {
success: true,
product: @purchase.json_data_for_mobile
}
end
def unarchive
@purchase.is_archived = false
@purchase.save!
render json: {
success: true,
product: @purchase.json_data_for_mobile
}
end
private
def fetch_purchase
@purchase = current_resource_owner.purchases.find_by_external_id(params[:id])
render json: { success: false, message: "Could not find purchase" }, status: :not_found if @purchase.nil? || (!@purchase.successful_and_not_reversed? && !@purchase.subscription)
end
def purchases_to_json(purchases)
purchases.map(&:json_data_for_mobile)
end
def search_options
@page = (params[:page] || 1).to_i
@items = (params[:items] || DEFAULT_SEARCH_RESULTS_SIZE).to_i
raise Pagy::VariableError.new(nil, :page, ">= 1", @page) if @page.zero? # manual validation
sort = (Array.wrap(params[:order]).presence || ["score", "date-desc"]).map do |order_by|
case order_by
when "score" then :_score
when "date-desc" then [{ created_at: :desc }, { id: :desc }]
when "date-asc" then [{ created_at: :asc }, { id: :asc }]
end
end.flatten.compact
options = {
buyer_query: params[:q],
purchaser: current_resource_owner,
state: Purchase::ALL_SUCCESS_STATES,
exclude_refunded_except_subscriptions: true,
exclude_unreversed_chargedback: true,
exclude_non_original_subscription_purchases: true,
exclude_deactivated_subscriptions: true,
exclude_bundle_product_purchases: true,
exclude_commission_completion_purchases: true,
track_total_hits: true,
from: ((@page - 1) * @items),
size: @items,
sort:,
aggs: {
seller_ids: { terms: { field: "seller_id" } }
}
}
options[:seller] = User.where(external_id: Array.wrap(params[:seller])) if params[:seller]
options[:archived] = ActiveModel::Type::Boolean.new.cast(params[:archived]) if params[:archived]
options
end
def formatted_sellers_agg(sellers_agg)
buckets = sellers_agg.buckets
sellers = User.where(id: buckets.pluck("key")).index_by(&:id)
buckets.map do |bucket|
seller = sellers.fetch(bucket["key"])
{
id: seller.external_id,
name: seller.name,
purchases_count: bucket["doc_count"]
}
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/consumption_analytics_controller.rb | app/controllers/api/mobile/consumption_analytics_controller.rb | # frozen_string_literal: true
class Api::Mobile::ConsumptionAnalyticsController < Api::Mobile::BaseController
include CreateConsumptionEvent
before_action { doorkeeper_authorize! :mobile_api }
def create
render json: { success: create_consumption_event!(params) }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/devices_controller.rb | app/controllers/api/mobile/devices_controller.rb | # frozen_string_literal: true
class Api::Mobile::DevicesController < Api::Mobile::BaseController
before_action { doorkeeper_authorize! :creator_api, :mobile_api }
def create
device = current_resource_owner.devices.build(device_params)
begin
saved = device.save
rescue ActiveRecord::RecordNotUnique
saved = false
end
if saved
render json: { success: true }, status: :created
else
render json: { success: false }, status: :unprocessable_entity
end
end
private
def device_params
params.require(:device).permit(:token, :device_type, :app_type, :app_version)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/url_redirects_controller.rb | app/controllers/api/mobile/url_redirects_controller.rb | # frozen_string_literal: true
class Api::Mobile::UrlRedirectsController < Api::Mobile::BaseController
before_action :fetch_url_redirect_by_external_id, only: :url_redirect_attributes
before_action :fetch_url_redirect_by_token, only: %i[stream hls_playlist download]
before_action :mark_rental_as_viewed, only: :hls_playlist
before_action :check_for_expired_rentals, only: %i[stream hls_playlist]
after_action :increment_product_uses_count, only: %i[stream download]
after_action -> { create_consumption_event!(ConsumptionEvent::EVENT_TYPE_WATCH) }, only: [:stream, :hls_playlist]
after_action -> { create_consumption_event!(ConsumptionEvent::EVENT_TYPE_DOWNLOAD) }, only: [:download]
before_action :fetch_product_file, only: %i[stream hls_playlist download]
def url_redirect_attributes
# By default the purchase is valid, this is because the url redirect could be generated by an admin
# and therefore would not have an associated purchase object
purchase_valid = @url_redirect.purchase ? @url_redirect.purchase.successful_and_valid? : true
render json: { success: true, product: @url_redirect.product_json_data, purchase_valid: }
end
def fetch_placeholder_products
render json: { success: true, placeholder_products: [] }
end
def stream
m3u8_playlist_link = api_mobile_hls_playlist_url(@url_redirect.token,
@product_file.external_id,
mobile_token: Api::Mobile::BaseController::MOBILE_TOKEN,
host: UrlService.api_domain_with_protocol)
render json: {
success: true,
playlist_url: @product_file.hls_playlist.nil? ? @url_redirect.signed_video_url(@product_file) : m3u8_playlist_link,
subtitles: @product_file.subtitle_files_for_mobile
}
end
def hls_playlist
hls_playlist_data = @product_file.hls_playlist
e404 if hls_playlist_data.blank?
render plain: hls_playlist_data, content_type: "application/x-mpegurl"
end
def download
redirect_to @url_redirect.signed_location_for_file(@product_file), allow_other_host: true
end
private
def fetch_product_file
@product_file = if @url_redirect.installment.present?
@url_redirect.installment.product_files.find_by_external_id(permitted_params[:product_file_id])
else
@url_redirect.product_file(permitted_params[:product_file_id])
end
e404 if @product_file.nil?
end
def mark_rental_as_viewed
@url_redirect.mark_rental_as_viewed!
end
def check_for_expired_rentals
return if !@url_redirect.is_rental || !@url_redirect.rental_expired?
render json: { success: false, message: "Your rental has expired." }, status: :unauthorized
end
def create_consumption_event!(event_type)
ConsumptionEvent.create_event!(
event_type:,
platform: ConsumptionEvent.determine_platform(request.user_agent),
url_redirect_id: @url_redirect.id,
product_file_id: @product_file&.id,
purchase_id: @url_redirect.purchase_id,
product_id: @url_redirect.purchase&.link_id || @url_redirect.link_id,
ip_address: request.remote_ip,
)
end
def permitted_params
params.permit(:product_file_id)
end
def increment_product_uses_count
return if @url_redirect.nil?
@url_redirect.increment!(:uses, 1)
@url_redirect.mark_as_seen
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/base_controller.rb | app/controllers/api/mobile/base_controller.rb | # frozen_string_literal: true
class Api::Mobile::BaseController < ApplicationController
include Pagy::Backend
before_action :check_mobile_token
rescue_from Pagy::VariableError do |exception|
render status: :bad_request, json: { error: { message: exception.message } }
end
# Secret token that mobile users must provide in each API call
MOBILE_TOKEN = GlobalConfig.get("MOBILE_TOKEN")
def current_resource_owner
impersonated_user || current_api_user
end
private
def check_mobile_token
fetch_error("Invalid request", status: :unauthorized) unless ActiveSupport::SecurityUtils.secure_compare(params[:mobile_token].to_s, MOBILE_TOKEN)
end
def fetch_url_redirect_by_external_id
@url_redirect = UrlRedirect.find_by_external_id(params[:id])
fetch_error("Could not find url redirect") if @url_redirect.nil?
end
def fetch_subscription_by_external_id
@subscription = Subscription.active.find_by_external_id(params[:id])
fetch_error("Could not find subscription") if @subscription.nil?
end
def fetch_url_redirect_by_token
@url_redirect = UrlRedirect.find_by(token: params[:token])
fetch_error("Could not find url redirect") if @url_redirect.nil?
end
def fetch_error(message, status: :not_found)
render json: { success: false, message: }, status:
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/sales_controller.rb | app/controllers/api/mobile/sales_controller.rb | # frozen_string_literal: true
class Api::Mobile::SalesController < Api::Mobile::BaseController
include ProcessRefund
before_action { doorkeeper_authorize! :mobile_api }
before_action :fetch_purchase, only: [:show]
def show
render json: { success: true, purchase: @purchase.json_data_for_mobile({ include_sale_details: true }) }
end
def refund
process_refund(seller: current_resource_owner, user: current_resource_owner,
purchase_external_id: params[:id], amount: params[:amount])
end
private
def fetch_purchase
@purchase = current_resource_owner.sales.find_by_external_id(params[:id])
fetch_error("Could not find purchase") if @purchase.nil?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/analytics_controller.rb | app/controllers/api/mobile/analytics_controller.rb | # frozen_string_literal: true
class Api::Mobile::AnalyticsController < Api::Mobile::BaseController
before_action -> { doorkeeper_authorize! :creator_api }
before_action :set_date_range, only: [:by_date, :by_state, :by_referral]
def data_by_date
data = SellerMobileAnalyticsService.new(current_resource_owner, range: params[:range], fields: [:sales_count, :purchases], query: params[:query]).process
render json: data
end
def revenue_totals
data = %w[day week month year].index_with do |range|
SellerMobileAnalyticsService.new(current_resource_owner, range:).process
end
render json: data
end
def by_date
service = CreatorAnalytics::CachingProxy.new(current_resource_owner)
options = {
group_by: params.fetch(:group_by, "day"),
days_without_years: true
}
data = service.data_for_dates(@start_date, @end_date, by: :date, options:)
render json: data
end
def by_state
data = CreatorAnalytics::CachingProxy.new(current_resource_owner).data_for_dates(@start_date, @end_date, by: :state)
render json: data
end
def by_referral
service = CreatorAnalytics::CachingProxy.new(current_resource_owner)
options = {
group_by: params.fetch(:group_by, "day"),
days_without_years: true
}
data = service.data_for_dates(@start_date, @end_date, by: :referral, options:)
render json: data
end
def products
pagination, records = pagy(current_resource_owner.products_for_creator_analytics, limit_max: nil, limit_param: :items)
render json: {
products: records.as_json(mobile: true),
meta: { pagination: PagyPresenter.new(pagination).metadata }
}
end
protected
def set_date_range
if params[:date_range]
@end_date = ActiveSupport::TimeZone[current_resource_owner.timezone].today
if params[:date_range] == "all"
@start_date = GUMROAD_STARTED_DATE
else
offset = { "1d" => 0, "1w" => 6, "1m" => 29, "1y" => 364 }.fetch(params[:date_range])
@start_date = @end_date - offset
end
elsif params[:start_date] && params[:end_date]
@end_date = Date.parse(params[:end_date])
@start_date = Date.parse(params[:start_date])
else
@end_date = ActiveSupport::TimeZone[current_resource_owner.timezone].today.to_date
@start_date = @end_date - 29
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/sessions_controller.rb | app/controllers/api/mobile/sessions_controller.rb | # frozen_string_literal: true
class Api::Mobile::SessionsController < Api::Mobile::BaseController
before_action { doorkeeper_authorize! :mobile_api }
skip_before_action :verify_authenticity_token, only: :create
def create
sign_in current_resource_owner
render json: { success: true, user: { email: current_resource_owner.form_email } }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/mobile/preorders_controller.rb | app/controllers/api/mobile/preorders_controller.rb | # frozen_string_literal: true
class Api::Mobile::PreordersController < Api::Mobile::BaseController
before_action :fetch_preorder_by_external_id, only: :preorder_attributes
def preorder_attributes
render json: { success: true, product: @preorder.mobile_json_data }
end
private
def fetch_preorder_by_external_id
@preorder = Preorder.authorization_successful_or_charge_successful.find_by_external_id(params[:id])
fetch_error("Could not find preorder") if @preorder.nil?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/product_public_files_controller.rb | app/controllers/api/internal/product_public_files_controller.rb | # frozen_string_literal: true
class Api::Internal::ProductPublicFilesController < Api::Internal::BaseController
include FetchProductByUniquePermalink
before_action :authenticate_user!
before_action :fetch_product_and_enforce_ownership, only: :create
after_action :verify_authorized
def create
authorize Link
public_file = @product.public_files.build
public_file.seller = current_seller
public_file.file.attach(params[:signed_blob_id])
if public_file.save
render json: { success: true, id: public_file.public_id }
else
render json: { success: false, error: public_file.errors.full_messages.first }
end
end
private
def fetch_product_and_enforce_ownership
@product = Link.find_by_external_id(params[:product_id])
e404 if @product.nil?
e404 if @product.user != current_seller
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/utm_links_controller.rb | app/controllers/api/internal/utm_links_controller.rb | # frozen_string_literal: true
class Api::Internal::UtmLinksController < Api::Internal::BaseController
before_action :authenticate_user!
after_action :verify_authorized
before_action :set_utm_link, only: [:edit, :update, :destroy]
before_action :authorize_user, only: [:edit, :update, :destroy]
def index
authorize UtmLink
json = PaginatedUtmLinksPresenter.new(
seller: current_seller,
query: index_params[:query],
page: index_params[:page],
sort: index_params[:sort]
).props
render json:
end
def new
authorize UtmLink
render json: UtmLinkPresenter.new(seller: current_seller).new_page_react_props(copy_from: params[:copy_from])
end
def create
authorize UtmLink
save_utm_link
end
def edit
render json: UtmLinkPresenter.new(seller: current_seller, utm_link: @utm_link).edit_page_react_props
end
def update
return e404_json if @utm_link.deleted?
save_utm_link
end
def destroy
@utm_link.mark_deleted!
head :ok
end
private
def index_params
params.permit(:query, :page, sort: [:key, :direction])
end
def set_utm_link
@utm_link = current_seller.utm_links.find_by_external_id(params[:id])
e404_json unless @utm_link
end
def authorize_user
authorize @utm_link
end
def render_error_response(error, attr_name: nil)
render json: { error:, attr_name: }, status: :unprocessable_entity
end
def permitted_params
params.require(:utm_link).permit(:title, :target_resource_type, :target_resource_id, :permalink, :utm_source, :utm_medium, :utm_campaign, :utm_term, :utm_content).merge(
ip_address: request.remote_ip,
browser_guid: cookies[:_gumroad_guid]
)
end
def save_utm_link
SaveUtmLinkService.new(seller: current_seller, params: permitted_params, utm_link: @utm_link).perform
head :ok
rescue ActiveRecord::RecordInvalid => e
error = e.record.errors.first
render_error_response(error.message, attr_name: error.attribute)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/carts_controller.rb | app/controllers/api/internal/carts_controller.rb | # frozen_string_literal: true
class Api::Internal::CartsController < Api::Internal::BaseController
def update
if permitted_cart_params[:items].length > Cart::MAX_ALLOWED_CART_PRODUCTS
return render json: { error: "You cannot add more than #{Cart::MAX_ALLOWED_CART_PRODUCTS} products to the cart." }, status: :unprocessable_entity
end
ActiveRecord::Base.transaction do
browser_guid = cookies[:_gumroad_guid]
cart = Cart.fetch_by(user: logged_in_user, browser_guid:) || Cart.new(user: logged_in_user, browser_guid:)
cart.ip_address = request.remote_ip
cart.browser_guid = browser_guid
cart.email = permitted_cart_params[:email].presence || logged_in_user&.email
cart.return_url = permitted_cart_params[:returnUrl]
cart.reject_ppp_discount = permitted_cart_params[:rejectPppDiscount] || false
cart.discount_codes = permitted_cart_params[:discountCodes].map { { code: _1[:code], fromUrl: _1[:fromUrl] } }
cart.save!
updated_cart_products = permitted_cart_params[:items].map do |item|
product = Link.find_by_external_id!(item[:product][:id])
option = item[:option_id].present? ? BaseVariant.find_by_external_id(item[:option_id]) : nil
cart_product = cart.cart_products.alive.find_or_initialize_by(product:, option:)
cart_product.affiliate = item[:affiliate_id].to_i.zero? ? nil : Affiliate.find_by_external_id_numeric(item[:affiliate_id].to_i)
accepted_offer = item[:accepted_offer]
if accepted_offer.present? && accepted_offer[:id].present?
cart_product.accepted_offer = Upsell.find_by_external_id(accepted_offer[:id])
cart_product.accepted_offer_details = {
original_product_id: accepted_offer[:original_product_id],
original_variant_id: accepted_offer[:original_variant_id],
}
end
cart_product.price = item[:price]
cart_product.quantity = item[:quantity]
cart_product.recurrence = item[:recurrence]
cart_product.recommended_by = item[:recommended_by]
cart_product.rent = item[:rent]
cart_product.url_parameters = item[:url_parameters]
cart_product.referrer = item[:referrer]
cart_product.recommender_model_name = item[:recommender_model_name]
cart_product.call_start_time = item[:call_start_time].present? ? Time.zone.parse(item[:call_start_time]) : nil
cart_product.pay_in_installments = !!item[:pay_in_installments] && product.allow_installment_plan?
cart_product.save!
cart_product
end
cart.alive_cart_products.where.not(id: updated_cart_products.map(&:id)).find_each(&:mark_deleted!)
end
head :no_content
rescue ActiveRecord::RecordInvalid => e
Bugsnag.notify(e)
Rails.logger.error(e.full_message) if Rails.env.development?
render json: { error: "Sorry, something went wrong. Please try again." }, status: :unprocessable_entity
end
private
def permitted_cart_params
params.require(:cart).permit(
:email, :returnUrl, :rejectPppDiscount,
discountCodes: [:code, :fromUrl],
items: [
:option_id, :affiliate_id, :price, :quantity, :recurrence, :recommended_by, :rent,
:referrer, :recommender_model_name, :call_start_time, :pay_in_installments,
url_parameters: {}, product: [:id], accepted_offer: [:id, :original_product_id, :original_variant_id],
]
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/ai_product_details_generations_controller.rb | app/controllers/api/internal/ai_product_details_generations_controller.rb | # frozen_string_literal: true
class Api::Internal::AiProductDetailsGenerationsController < Api::Internal::BaseController
include Throttling
before_action :authenticate_user!
before_action :throttle_ai_requests
after_action :verify_authorized
AI_REQUESTS_PER_PERIOD = 10
AI_REQUESTS_PERIOD_WINDOW = 1.hour
private_constant :AI_REQUESTS_PER_PERIOD, :AI_REQUESTS_PERIOD_WINDOW
def create
authorize current_seller, :generate_product_details_with_ai?
prompt = params[:prompt]
if prompt.blank?
render json: { error: "Prompt is required" }, status: :bad_request
return
end
begin
service = ::Ai::ProductDetailsGeneratorService.new(current_seller: current_seller)
result = service.generate_product_details(prompt: sanitize_prompt(prompt))
render json: {
success: true,
data: {
name: result[:name],
description: result[:description],
summary: result[:summary],
number_of_content_pages: result[:number_of_content_pages],
price: result[:price],
currency_code: result[:currency_code],
price_frequency_in_months: result[:price_frequency_in_months],
native_type: result[:native_type],
duration_in_seconds: result[:duration_in_seconds]
}
}
rescue => e
Rails.logger.error "Product details generation using AI failed: #{e.full_message}"
Bugsnag.notify(e)
render json: {
success: false,
error: "Failed to generate product details. Please try again."
}, status: :internal_server_error
end
end
private
def throttle_ai_requests
return unless current_user
key = RedisKey.ai_request_throttle(current_seller.id)
throttle!(key:, limit: AI_REQUESTS_PER_PERIOD, period: AI_REQUESTS_PERIOD_WINDOW)
end
def sanitize_prompt(prompt)
sanitized = prompt.gsub(/\b(ignore|forget|system|assistant|user|delete|remove|clear|impersonate)\s+(previous|above|all)\b/i, "[FILTERED]")
sanitized.gsub(/[^\w\s.,!?\-\[\]]/, "").strip
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/collaborators_controller.rb | app/controllers/api/internal/collaborators_controller.rb | # frozen_string_literal: true
class Api::Internal::CollaboratorsController < Api::Internal::BaseController
before_action :authenticate_user!
before_action :set_collaborator, only: %i[edit update destroy]
before_action :authorize_user
after_action :verify_authorized
def index
render json: CollaboratorsPresenter.new(seller: pundit_user.seller).index_props
end
def new
render json: CollaboratorPresenter.new(seller: pundit_user.seller).new_collaborator_props
end
def create
response = Collaborator::CreateService.new(seller: current_seller, params: collaborator_params).process
render json: response, status: response[:success] ? :created : :unprocessable_entity
end
def edit
render json: CollaboratorPresenter.new(seller: pundit_user.seller, collaborator: @collaborator).edit_collaborator_props
end
def update
response = Collaborator::UpdateService.new(seller: current_seller, collaborator_id: params[:id], params: collaborator_params).process
render json: response, status: response[:success] ? :ok : :unprocessable_entity
end
def destroy
@collaborator.mark_deleted!
if current_seller == @collaborator.seller
AffiliateMailer.collaboration_ended_by_seller(@collaborator.id).deliver_later
elsif current_seller == @collaborator.affiliate_user
AffiliateMailer.collaboration_ended_by_affiliate_user(@collaborator.id).deliver_later
end
head :no_content
end
private
def collaborator_params
params.require(:collaborator).permit(:email, :apply_to_all_products, :percent_commission, :dont_show_as_co_creator, products: [:id, :percent_commission, :dont_show_as_co_creator])
end
def authorize_user
if @collaborator.present?
authorize @collaborator
else
authorize Collaborator
end
end
def set_collaborator
@collaborator = Collaborator.alive.find_by_external_id(params[:id]) || e404
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/base_controller.rb | app/controllers/api/internal/base_controller.rb | # frozen_string_literal: true
class Api::Internal::BaseController < ApplicationController
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/existing_product_files_controller.rb | app/controllers/api/internal/existing_product_files_controller.rb | # frozen_string_literal: true
class Api::Internal::ExistingProductFilesController < Api::Internal::BaseController
include FetchProductByUniquePermalink
before_action :authenticate_user!
before_action :fetch_product_by_unique_permalink, only: :index
def index
e404 if @product.user != current_seller
render json: { existing_files: ProductPresenter.new(product: @product, pundit_user:).existing_files }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/home_page_numbers_controller.rb | app/controllers/api/internal/home_page_numbers_controller.rb | # frozen_string_literal: true
class Api::Internal::HomePageNumbersController < Api::Internal::BaseController
include ActionView::Helpers::NumberHelper
def index
home_page_numbers = Rails.cache.fetch("homepage_numbers", expires_in: 1.day) do
prev_week_payout_usd = $redis.get(RedisKey.prev_week_payout_usd)
{
prev_week_payout_usd: "$#{number_with_delimiter(prev_week_payout_usd)}"
}
end
render json: home_page_numbers
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/product_posts_controller.rb | app/controllers/api/internal/product_posts_controller.rb | # frozen_string_literal: true
class Api::Internal::ProductPostsController < Api::Internal::BaseController
include FetchProductByUniquePermalink
before_action :authenticate_user!
before_action :fetch_product_by_unique_permalink, only: :index
def index
e404 if @product.user != current_seller
render json: PaginatedProductPostsPresenter.new(product: @product, variant_external_id: params[:variant_id], options: { page: params[:page] }).index_props
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/communities_controller.rb | app/controllers/api/internal/communities_controller.rb | # frozen_string_literal: true
class Api::Internal::CommunitiesController < Api::Internal::BaseController
before_action :authenticate_user!
after_action :verify_authorized
def index
authorize Community
render json: CommunitiesPresenter.new(current_user: current_seller).props
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/receipt_previews_controller.rb | app/controllers/api/internal/receipt_previews_controller.rb | # frozen_string_literal: true
class Api::Internal::ReceiptPreviewsController < Api::Internal::BaseController
include FetchProductByUniquePermalink
before_action :authenticate_user!
before_action :fetch_product_by_unique_permalink
def show
e404 if @product.nil? || @product.user != current_seller
@product.custom_receipt_text = params[:custom_receipt_text]
@product.custom_view_content_button_text = params[:custom_view_content_button_text]
purchase_preview = build_purchase_preview
unless purchase_preview.valid?
error_message = purchase_preview.errors.full_messages.join(", ")
return render html: "Error: #{error_message}", status: :unprocessable_entity
end
rendered_html = ApplicationController.renderer.render(
template: "customer_mailer/receipt",
layout: "email",
assigns: {
chargeable: purchase_preview,
receipt_presenter: ReceiptPresenter.new(purchase_preview, for_email: false)
}
)
premailer = Premailer::Rails::CustomizedPremailer.new(rendered_html)
render html: premailer.to_inline_css.html_safe, layout: false
end
private
def build_purchase_preview
price_cents = @product.price_cents || 0
purchase_preview = PurchasePreview.new(
link: @product,
seller: @product.user,
created_at: Time.current,
quantity: 1,
custom_fields: [],
formatted_total_display_price_per_unit: MoneyFormatter.format(price_cents, @product.price_currency_type.to_sym, no_cents_if_whole: true, symbol: true),
shipping_cents: 0,
displayed_price_currency_type: @product.price_currency_type,
url_redirect: OpenStruct.new(
token: "preview_token"
),
displayed_price_cents: price_cents,
support_email: @product.user.support_or_form_email,
charged_amount_cents: price_cents,
external_id_for_invoice: "preview_order_id"
)
purchase_preview.unbundled_purchases = [purchase_preview]
purchase_preview.successful_purchases = [purchase_preview]
purchase_preview.orderable = purchase_preview
purchase_preview
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/communities/chat_messages_controller.rb | app/controllers/api/internal/communities/chat_messages_controller.rb | # frozen_string_literal: true
class Api::Internal::Communities::ChatMessagesController < Api::Internal::BaseController
before_action :authenticate_user!
before_action :set_community
before_action :set_message, only: [:update, :destroy]
after_action :verify_authorized
def index
render json: PaginatedCommunityChatMessagesPresenter.new(community: @community, timestamp: params[:timestamp], fetch_type: params[:fetch_type]).props
end
def create
message = @community.community_chat_messages.build(permitted_params)
message.user = current_seller
if message.save
message_props = CommunityChatMessagePresenter.new(message:).props
broadcast_message(message_props, CommunityChannel::CREATE_CHAT_MESSAGE_TYPE)
render json: { message: message_props }
else
render json: { error: message.errors.full_messages.first }, status: :unprocessable_entity
end
end
def update
if @message.update(permitted_params)
message_props = CommunityChatMessagePresenter.new(message: @message).props
broadcast_message(message_props, CommunityChannel::UPDATE_CHAT_MESSAGE_TYPE)
render json: { message: message_props }
else
render json: { error: @message.errors.full_messages.first }, status: :unprocessable_entity
end
end
def destroy
@message.mark_deleted!
message_props = CommunityChatMessagePresenter.new(message: @message).props
broadcast_message(message_props, CommunityChannel::DELETE_CHAT_MESSAGE_TYPE)
head :ok
end
private
def set_community
@community = Community.find_by_external_id(params[:community_id])
return e404_json unless @community
authorize @community, :show?
end
def set_message
@message = @community.community_chat_messages.find_by_external_id(params[:id])
return e404_json unless @message
authorize @message
end
def permitted_params
params.require(:community_chat_message).permit(:content)
end
def broadcast_message(message_props, type)
CommunityChannel.broadcast_to(
"community_#{@community.external_id}",
{ type:, message: message_props },
)
rescue => e
Rails.logger.error("Error broadcasting message to community channel: #{e.message}")
Bugsnag.notify(e)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/communities/last_read_chat_messages_controller.rb | app/controllers/api/internal/communities/last_read_chat_messages_controller.rb | # frozen_string_literal: true
class Api::Internal::Communities::LastReadChatMessagesController < Api::Internal::BaseController
before_action :authenticate_user!
before_action :set_community
after_action :verify_authorized
def create
message = @community.community_chat_messages.find_by_external_id(params[:message_id])
return e404_json unless message
params = { user_id: current_seller.id, community_id: @community.id, community_chat_message_id: message.id }
last_read_message = LastReadCommunityChatMessage.set!(**params)
render json: { unread_count: LastReadCommunityChatMessage.unread_count_for(**params.merge(community_chat_message_id: last_read_message.community_chat_message_id)) }
end
private
def set_community
@community = Community.find_by_external_id(params[:community_id])
return e404_json unless @community
authorize @community, :show?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/communities/notification_settings_controller.rb | app/controllers/api/internal/communities/notification_settings_controller.rb | # frozen_string_literal: true
class Api::Internal::Communities::NotificationSettingsController < Api::Internal::BaseController
before_action :authenticate_user!
before_action :set_community
after_action :verify_authorized
def update
settings = current_seller.community_notification_settings.find_or_initialize_by(seller: @community.seller)
settings.update!(permitted_params)
render json: { settings: CommunityNotificationSettingPresenter.new(settings:).props }
end
private
def set_community
@community = Community.find_by_external_id(params[:community_id])
return e404_json unless @community
authorize @community, :show?
end
def permitted_params
params.require(:settings).permit(:recap_frequency)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/installments/recipient_counts_controller.rb | app/controllers/api/internal/installments/recipient_counts_controller.rb | # frozen_string_literal: true
class Api::Internal::Installments::RecipientCountsController < Api::Internal::BaseController
before_action :authenticate_user!
after_action :verify_authorized
def show
authorize Installment, :updated_recipient_count?
permitted_params = params.permit(
:paid_more_than_cents,
:paid_less_than_cents,
:bought_from,
:installment_type,
:created_after,
:created_before,
bought_products: [],
bought_variants: [],
not_bought_products: [],
not_bought_variants: [],
affiliate_products: []
)
installment = Installment.new(permitted_params)
installment.seller = current_seller
render json: {
audience_count: current_seller.audience_members.count,
recipient_count: installment.audience_members_count
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/installments/preview_emails_controller.rb | app/controllers/api/internal/installments/preview_emails_controller.rb | # frozen_string_literal: true
class Api::Internal::Installments::PreviewEmailsController < Api::Internal::BaseController
before_action :authenticate_user!
after_action :verify_authorized
def create
installment = current_seller.installments.alive.find_by_external_id(params[:id])
return e404_json unless installment
authorize installment, :preview?
installment.send_preview_email(impersonating_user || logged_in_user)
head :ok
rescue Installment::PreviewEmailError => e
render json: { message: e.message }, status: :unprocessable_entity
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/installments/audience_counts_controller.rb | app/controllers/api/internal/installments/audience_counts_controller.rb | # frozen_string_literal: true
class Api::Internal::Installments::AudienceCountsController < Api::Internal::BaseController
before_action :authenticate_user!
after_action :verify_authorized
def show
installment = current_seller.installments.alive.find_by_external_id(params[:id])
return e404_json unless installment
authorize installment, :updated_audience_count?
render json: { count: installment.audience_members_count }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/collaborators/invitation_acceptances_controller.rb | app/controllers/api/internal/collaborators/invitation_acceptances_controller.rb | # frozen_string_literal: true
class Api::Internal::Collaborators::InvitationAcceptancesController < Api::Internal::BaseController
before_action :authenticate_user!
before_action :set_collaborator!
before_action :set_invitation!
after_action :verify_authorized
def create
authorize @invitation, :accept?
@invitation.accept!
head :ok
end
private
def set_collaborator!
@collaborator = Collaborator.alive.find_by_external_id!(params[:collaborator_id])
end
def set_invitation!
@invitation = @collaborator.collaborator_invitation || e404
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/collaborators/incomings_controller.rb | app/controllers/api/internal/collaborators/incomings_controller.rb | # frozen_string_literal: true
class Api::Internal::Collaborators::IncomingsController < Api::Internal::BaseController
before_action :authenticate_user!
after_action :verify_authorized
def index
authorize Collaborator
incoming_collaborators = scoped_incoming_collaborators
render json: {
collaborators_disabled_reason:,
collaborators: incoming_collaborators.map do |collaborator|
{
id: collaborator.external_id,
seller_email: collaborator.seller.email,
seller_name: collaborator.seller.display_name(prefer_email_over_default_username: true),
seller_avatar_url: collaborator.seller.avatar_url,
apply_to_all_products: collaborator.apply_to_all_products,
affiliate_percentage: collaborator.affiliate_percentage,
dont_show_as_co_creator: collaborator.dont_show_as_co_creator,
invitation_accepted: collaborator.invitation_accepted?,
products: collaborator.product_affiliates.map do |product_affiliate|
{
id: product_affiliate.product.external_id,
url: product_affiliate.product.long_url,
name: product_affiliate.product.name,
affiliate_percentage: product_affiliate.affiliate_percentage,
dont_show_as_co_creator: product_affiliate.dont_show_as_co_creator,
}
end
}
end
}
end
private
def collaborators_disabled_reason
current_seller.has_brazilian_stripe_connect_account? ? "Collaborators with Brazilian Stripe accounts are not supported." : nil
end
def scoped_incoming_collaborators
Collaborator
.alive
.where(affiliate_user: current_seller)
.includes(
:collaborator_invitation,
:seller,
product_affiliates: :product
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/collaborators/invitation_declines_controller.rb | app/controllers/api/internal/collaborators/invitation_declines_controller.rb | # frozen_string_literal: true
class Api::Internal::Collaborators::InvitationDeclinesController < Api::Internal::BaseController
before_action :authenticate_user!
before_action :set_collaborator!
before_action :set_invitation!
after_action :verify_authorized
def create
authorize @invitation, :decline?
@invitation.decline!
head :ok
end
private
def set_collaborator!
@collaborator = Collaborator.find_by_external_id!(params[:collaborator_id])
end
def set_invitation!
@invitation = @collaborator.collaborator_invitation || e404
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/utm_links/stats_controller.rb | app/controllers/api/internal/utm_links/stats_controller.rb | # frozen_string_literal: true
class Api::Internal::UtmLinks::StatsController < Api::Internal::BaseController
before_action :authenticate_user!
after_action :verify_authorized
def index
authorize UtmLink
utm_link_ids = current_seller.utm_links.by_external_ids(params[:ids]).pluck(:id)
render json: UtmLinksStatsPresenter.new(seller: current_seller, utm_link_ids:).props
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/utm_links/unique_permalinks_controller.rb | app/controllers/api/internal/utm_links/unique_permalinks_controller.rb | # frozen_string_literal: true
class Api::Internal::UtmLinks::UniquePermalinksController < Api::Internal::BaseController
before_action :authenticate_user!
after_action :verify_authorized
def show
authorize UtmLink, :new?
render json: { permalink: UtmLink.generate_permalink }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/helper/instant_payouts_controller.rb | app/controllers/api/internal/helper/instant_payouts_controller.rb | # frozen_string_literal: true
class Api::Internal::Helper::InstantPayoutsController < Api::Internal::Helper::BaseController
include CurrencyHelper
before_action :fetch_user
INSTANT_PAYOUT_BALANCE_OPENAPI = {
summary: "Get instant payout balance",
description: "Get the amount available for instant payout for a user",
parameters: [
{
name: "email",
in: "query",
required: true,
schema: {
type: "string"
},
description: "Email address of the seller"
}
],
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully retrieved instant payout balance",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
balance: { type: "string" }
},
required: ["success", "balance"]
}
}
}
},
'404': {
description: "User not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
}
}
}.freeze
def index
balance_cents = @user.instantly_payable_unpaid_balance_cents
render json: {
success: true,
balance: formatted_dollar_amount(balance_cents)
}
end
CREATE_INSTANT_PAYOUT_OPENAPI = {
summary: "Create new instant payout",
description: "Create a new instant payout for a user",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
email: { type: "string", description: "Email address of the seller" }
},
required: ["email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully created instant payout",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true }
},
required: ["success"]
}
}
}
},
'404': {
description: "User not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
},
'422': {
description: "Unable to create instant payout",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
}
}
}.freeze
def create
result = InstantPayoutsService.new(@user).perform
if result[:success]
render json: { success: true }
else
render json: { success: false, message: result[:error] }, status: :unprocessable_entity
end
end
private
def fetch_user
if params[:email].blank?
render json: { success: false, message: "Email is required" }, status: :unprocessable_entity
return
end
@user = User.alive.by_email(params[:email]).first
render json: { success: false, message: "User not found" }, status: :not_found unless @user
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/helper/purchases_controller.rb | app/controllers/api/internal/helper/purchases_controller.rb | # frozen_string_literal: true
class Api::Internal::Helper::PurchasesController < Api::Internal::Helper::BaseController
before_action :fetch_last_purchase, only: [:refund_last_purchase, :resend_last_receipt]
REFUND_LAST_PURCHASE_OPENAPI = {
summary: "Refund last purchase",
description: "Refund last purchase based on the customer email, should be used when within product refund policy",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
email: { type: "string", description: "Email address of the customer" }
},
required: ["email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully refunded purchase",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { type: "string" }
}
}
}
}
},
'422': {
description: "Purchase not found or not refundable",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
}
}
}.freeze
def refund_last_purchase
if @purchase.present? && @purchase.refund_and_save!(GUMROAD_ADMIN_ID)
render json: { success: true, message: "Successfully refunded purchase number #{@purchase.external_id_numeric}" }
else
render json: { success: false, message: @purchase.present? ? @purchase.errors.full_messages.to_sentence : "Purchase not found" }, status: :unprocessable_entity
end
end
RESEND_LAST_RECEIPT_OPENAPI = {
summary: "Resend receipt",
description: "Resend last receipt to customer",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
email: { type: "string", description: "Email address of the customer" }
},
required: ["email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully resent receipt",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { type: "string" }
}
}
}
},
},
'422': {
description: "Purchase not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
},
}
}.freeze
def resend_last_receipt
@purchase.resend_receipt
render json: { success: true, message: "Successfully resent receipt for purchase number #{@purchase.external_id_numeric}" }
end
RESEND_ALL_RECEIPTS_OPENAPI = {
summary: "Resend all receipts",
description: "Resend all receipt emails to customer for all their purchases",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
email: { type: "string", description: "Email address of the customer" }
},
required: ["email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully resent all receipts",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { type: "string" },
count: { type: "integer" }
}
}
}
},
},
'404': {
description: "No purchases found for email",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
},
}
}.freeze
def resend_all_receipts
purchases = Purchase.where(email: params[:email]).successful
return render json: { success: false, message: "No purchases found for email: #{params[:email]}" }, status: :not_found if purchases.empty?
CustomerMailer.grouped_receipt(purchases.ids).deliver_later(queue: "critical")
render json: {
success: true,
message: "Successfully resent all receipts to #{params[:email]}",
count: purchases.count
}
end
SEARCH_PURCHASE_OPENAPI = {
summary: "Search purchase",
description: "Search purchase by query (order ID, email, IP, or card fingerprint), seller, license key, or card details. At least one parameter is required.",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
query: { type: "string", description: "Search by order ID, card fingerprint, or IP address" },
email: { type: "string", description: "Email address of the customer/buyer" },
creator_email: { type: "string", description: "Email address of the creator/seller" },
license_key: { type: "string", description: "Product license key (4 groups of alphanumeric characters separated by dashes)" },
charge_amount: { type: "number", description: "Charge amount in dollars" },
purchase_date: { type: "string", description: "Purchase date in YYYY-MM-DD format" },
card_type: { type: "string", description: "Card type" },
card_last4: { type: "string", description: "Last 4 digits of the card" }
},
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Purchase found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { const: "Purchase found" },
purchase: {
type: "object",
properties: {
id: { type: "integer" },
email: { type: "string" },
link_name: { type: "string" },
price_cents: { type: "integer" },
purchase_state: { type: "string" },
created_at: { type: "string", format: "date-time" },
receipt_url: { type: "string", format: "uri" },
seller_email: { type: "string", description: "Email address of the product seller" }
}
}
}
}
}
}
},
'404': {
description: "Purchase not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { const: "Purchase not found" }
}
}
}
}
},
'400': {
description: "Invalid date format",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { const: "purchase_date must use YYYY-MM-DD format." }
}
}
}
}
}
}
}.freeze
def search
search_params = {
query: params[:query],
email: params[:email],
creator_email: params[:creator_email],
license_key: params[:license_key],
transaction_date: params[:purchase_date],
price: params[:charge_amount].present? ? params[:charge_amount].to_f : nil,
card_type: params[:card_type],
last_4: params[:card_last4],
}
return render json: { success: false, message: "At least one of the parameters is required." }, status: :bad_request if search_params.compact.blank?
purchase = AdminSearchService.new.search_purchases(**search_params, limit: 1).first
return render json: { success: false, message: "Purchase not found" }, status: :not_found if purchase.nil?
purchase_json = purchase.slice(:email, :link_name, :price_cents, :purchase_state, :created_at)
purchase_json[:id] = purchase.external_id_numeric
purchase_json[:seller_email] = purchase.seller_email
purchase_json[:receipt_url] = receipt_purchase_url(purchase.external_id, host: UrlService.domain_with_protocol, email: purchase.email)
if purchase.refunded?
purchase_json[:refund_status] = "refunded"
elsif purchase.stripe_partially_refunded
purchase_json[:refund_status] = "partially_refunded"
else
purchase_json[:refund_status] = nil
end
if purchase.amount_refunded_cents > 0
purchase_json[:refund_amount] = purchase.amount_refunded_cents
end
if purchase_json[:refund_status]
purchase_json[:refund_date] = purchase.refunds.order(:created_at).last&.created_at
end
render json: { success: true, message: "Purchase found", purchase: purchase_json }
rescue AdminSearchService::InvalidDateError
render json: { success: false, message: "purchase_date must use YYYY-MM-DD format." }, status: :bad_request
end
RESEND_RECEIPT_BY_NUMBER_OPENAPI = {
summary: "Resend receipt by purchase number",
description: "Resend receipt to customer using purchase number",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
purchase_number: { type: "string", description: "Purchase number/ID" }
},
required: ["purchase_number"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully resent receipt",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { type: "string" }
}
}
}
},
},
'404': {
description: "Purchase not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
},
}
}.freeze
def resend_receipt_by_number
purchase = Purchase.find_by_external_id_numeric(params[:purchase_number].to_i)
return e404_json unless purchase.present?
purchase.resend_receipt
render json: { success: true, message: "Successfully resent receipt for purchase number #{purchase.external_id_numeric} to #{purchase.email}" }
end
REFRESH_LIBRARY_OPENAPI = {
summary: "Refresh purchases in user's library",
description: "Link purchases with missing purchaser_id to the user account for the given email address",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
email: { type: "string", description: "Email address of the customer" }
},
required: ["email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully refreshed library",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { type: "string" },
count: { type: "integer" }
}
}
}
}
},
'404': {
description: "User not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
}
}
}.freeze
def refresh_library
email = params[:email]
return render json: { success: false, message: "Email address is required" }, status: :bad_request unless email.present?
user = User.find_by(email: email)
return render json: { success: false, message: "No user found with email: #{email}" }, status: :not_found unless user.present?
count = Purchase.where(email: user.email, purchaser_id: nil).update_all(purchaser_id: user.id)
render json: {
success: true,
message: "Successfully refreshed library for #{email}. Updated #{count} purchases.",
count: count
}
end
REASSIGN_PURCHASES_OPENAPI = {
summary: "Reassign purchases",
description: "Update the email on all purchases belonging to the 'from' email address to the 'to' email address",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
from: { type: "string", description: "Source email address" },
to: { type: "string", description: "Target email address" }
},
required: ["from", "to"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully reassigned purchases",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { type: "string" },
count: { type: "integer" }
}
}
}
}
},
'400': {
description: "Missing required parameters",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
},
'404': {
description: "No purchases found for the given email",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
}
}
}.freeze
def reassign_purchases
from_email = params[:from]
to_email = params[:to]
return render json: { success: false, message: "Both 'from' and 'to' email addresses are required" }, status: :bad_request unless from_email.present? && to_email.present?
purchases = Purchase.where(email: from_email)
return render json: { success: false, message: "No purchases found for email: #{from_email}" }, status: :not_found if purchases.empty?
target_user = User.find_by(email: to_email)
reassigned_purchase_ids = []
purchases.each do |purchase|
purchase.email = to_email
if purchase.subscription.present? && !purchase.is_original_subscription_purchase? && !purchases.include?(purchase.original_purchase)
purchase.original_purchase.update(email: to_email)
reassigned_purchase_ids << purchase.original_purchase.id if purchase.original_purchase.saved_changes?
end
purchase.purchaser_id = target_user&.id
if purchase.is_original_subscription_purchase? && purchase.subscription.present?
if target_user
purchase.subscription.user = target_user
purchase.subscription.save
else
purchase.subscription.user = nil
purchase.subscription.save
end
end
if purchase.save
reassigned_purchase_ids << purchase.id
end
end
if reassigned_purchase_ids.any?
CustomerMailer.grouped_receipt(reassigned_purchase_ids).deliver_later(queue: "critical")
end
render json: {
success: true,
message: "Successfully reassigned #{reassigned_purchase_ids.size} purchases from #{from_email} to #{to_email}. Receipt sent to #{to_email}.",
count: reassigned_purchase_ids.size,
reassigned_purchase_ids: reassigned_purchase_ids
}
end
AUTO_REFUND_PURCHASE_OPENAPI = {
summary: "Auto-refund purchase",
description: "Allow customers to automatically refund their own purchase. The tool will determine refund eligibility based on refund policy timeframe and absence of fine-print conditions",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
purchase_id: { type: "string", description: "Purchase ID/number to refund (also referred to as order ID). Can be retrieved using search_purchase endpoint and is not placeholder information" },
email: { type: "string", description: "Email address of the customer, must match purchase" }
},
required: ["purchase_id", "email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully refunded purchase",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { type: "string" }
}
}
}
}
},
'422': {
description: "Purchase not refundable",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
},
'404': {
description: "Purchase not found or email mismatch",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
}
}
}.freeze
def auto_refund_purchase
purchase_id = params[:purchase_id].to_i
email = params[:email]
purchase = Purchase.find_by_external_id_numeric(purchase_id)
unless purchase && purchase.email.downcase == email.downcase
return render json: { success: false, message: "Purchase not found or email doesn't match" }, status: :not_found
end
unless purchase.within_refund_policy_timeframe?
return render json: { success: false, message: "Purchase is outside of the refund policy timeframe" }, status: :unprocessable_entity
end
if purchase.purchase_refund_policy&.fine_print.present?
return render json: { success: false, message: "This product has specific refund conditions that require seller review" }, status: :unprocessable_entity
end
if purchase.refund_and_save!(GUMROAD_ADMIN_ID)
render json: { success: true, message: "Successfully refunded purchase number #{purchase.external_id_numeric}" }
else
render json: { success: false, message: "Refund failed for purchase number #{purchase.external_id_numeric}" }, status: :unprocessable_entity
end
end
REFUND_TAXES_ONLY_OPENAPI = {
summary: "Refund taxes only",
description: "Refund only the tax portion of a purchase for tax-exempt customers. Does not refund the product price.",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
purchase_id: { type: "string", description: "Purchase ID/number to refund taxes for" },
email: { type: "string", description: "Email address of the customer, must match purchase" },
note: { type: "string", description: "Optional note for the refund" },
business_vat_id: { type: "string", description: "Optional business VAT ID for invoice generation" }
},
required: ["purchase_id", "email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully refunded taxes",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { type: "string" }
}
}
}
}
},
'422': {
description: "No refundable taxes or refund failed",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
},
'404': {
description: "Purchase not found or email mismatch",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
}
}
}.freeze
def refund_taxes_only
purchase_id = params[:purchase_id]&.to_i
email = params[:email]
return render json: { success: false, message: "Both 'purchase_id' and 'email' parameters are required" }, status: :bad_request unless purchase_id.present? && email.present?
purchase = Purchase.find_by_external_id_numeric(purchase_id)
unless purchase && purchase.email.downcase == email.downcase
return render json: { success: false, message: "Purchase not found or email doesn't match" }, status: :not_found
end
if purchase.refund_gumroad_taxes!(refunding_user_id: GUMROAD_ADMIN_ID, note: params[:note], business_vat_id: params[:business_vat_id])
render json: { success: true, message: "Successfully refunded taxes for purchase number #{purchase.external_id_numeric}" }
else
error_message = purchase.errors.full_messages.presence&.to_sentence || "No refundable taxes available"
render json: { success: false, message: error_message }, status: :unprocessable_entity
end
end
private
def fetch_last_purchase
@purchase = Purchase.where(email: params[:email]).order(created_at: :desc).first
e404_json unless @purchase
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/helper/users_controller.rb | app/controllers/api/internal/helper/users_controller.rb | # frozen_string_literal: true
class Api::Internal::Helper::UsersController < Api::Internal::Helper::BaseController
skip_before_action :authorize_helper_token!, only: [:user_info]
before_action :authorize_hmac_signature!, only: [:user_info]
def user_info
render json: { success: false, error: "'email' parameter is required" }, status: :bad_request if params[:email].blank?
render json: {
success: true,
customer: HelperUserInfoService.new(email: params[:email]).customer_info,
}
end
USER_SUSPENSION_INFO_OPENAPI = {
summary: "Get user suspension information",
description: "Retrieve suspension status and details for a user",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
email: { type: "string", description: "Email address of the user" }
},
required: ["email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully retrieved user suspension information",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { type: "boolean" },
status: { type: "string", description: "Status of the user" },
updated_at: { type: "string", format: "date-time", nullable: true, description: "When the user's suspension status was last updated" },
appeal_url: { type: "string", nullable: true, description: "URL for the user to appeal their suspension" }
}
}
}
}
},
'400': {
description: "Missing required parameters",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
error: { type: "string" }
}
}
}
}
},
'422': {
description: "User not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
error_message: { type: "string" }
}
}
}
}
}
}
}.freeze
def user_suspension_info
if params[:email].blank?
render json: { success: false, error: "'email' parameter is required" }, status: :bad_request
return
end
user = User.alive.by_email(params[:email]).first
if user.blank?
return render json: { success: false, error_message: "An account does not exist with that email." }, status: :unprocessable_entity
end
iffy_url = Rails.env.production? ? "https://api.iffy.com/api/v1/users" : "http://localhost:3000/api/v1/users"
begin
if user.suspended?
render json: {
success: true,
status: "Suspended",
updated_at: user.comments.where(comment_type: [Comment::COMMENT_TYPE_SUSPENSION_NOTE, Comment::COMMENT_TYPE_SUSPENDED]).order(created_at: :desc).first&.created_at,
appeal_url: nil
}
return
end
response = HTTParty.get(
"#{iffy_url}?email=#{CGI.escape(params[:email])}",
headers: {
"Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}"
}
)
if response.success? && response.parsed_response["data"].present? && !response.parsed_response["data"].empty?
user_data = response.parsed_response["data"].first
render json: {
success: true,
status: user_data["actionStatus"],
updated_at: user_data["actionStatusCreatedAt"],
appeal_url: user_data["appealUrl"]
}
else
render json: {
success: true,
status: "Compliant",
updated_at: nil,
appeal_url: nil
}
end
rescue HTTParty::Error, Net::OpenTimeout, Net::ReadTimeout, Timeout::Error, Errno::ECONNREFUSED, SocketError => e
Bugsnag.notify(e)
render json: {
success: false,
error_message: "Failed to retrieve suspension information"
}, status: :service_unavailable
end
end
SEND_RESET_PASSWORD_INSTRUCTIONS_OPENAPI = {
summary: "Initiate password reset",
description: "Send email with instructions to reset password",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
email: { type: "string", description: "Email address of the customer" }
},
required: ["email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully sent reset password instructions",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { type: "string" }
}
}
}
}
},
'422': {
description: "Email invalid or user not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
},
}
}.freeze
def send_reset_password_instructions
if EmailFormatValidator.valid?(params[:email])
user = User.alive.by_email(params[:email]).first
if user
user.send_reset_password_instructions
render json: { success: true, message: "Reset password instructions sent" }
else
render json: { error_message: "An account does not exist with that email." },
status: :unprocessable_entity
end
else
render json: { error_message: "Invalid email" }, status: :unprocessable_entity
end
end
UPDATE_EMAIL_OPENAPI = {
summary: "Update user email",
description: "Update a user's email address",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
current_email: { type: "string", description: "Current email address of the user" },
new_email: { type: "string", description: "New email address for the user" }
},
required: ["current_email", "new_email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully updated email",
content: {
'application/json': {
schema: {
type: "object",
properties: {
message: { type: "string" }
}
}
}
}
},
'422': {
description: "Invalid email or user not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
error_message: { type: "string" }
}
}
}
}
}
}
}.freeze
def update_email
if params[:current_email].blank? || params[:new_email].blank?
render json: { error_message: "Both current and new email are required." }, status: :unprocessable_entity
return
end
if !EmailFormatValidator.valid?(params[:new_email])
render json: { error_message: "Invalid new email format." }, status: :unprocessable_entity
return
end
user = User.alive.by_email(params[:current_email]).first
if user
user.email = params[:new_email]
if user.save
render json: { message: "Email updated." }
else
render json: { error_message: user.errors.full_messages.join(", ") }, status: :unprocessable_entity
end
else
render json: { error_message: "An account does not exist with that email." }, status: :unprocessable_entity
end
end
UPDATE_TWO_FACTOR_AUTHENTICATION_ENABLED_OPENAPI = {
summary: "Update two-factor authentication status",
description: "Update a user's two-factor authentication enabled status",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
email: { type: "string", description: "Email address of the user" },
enabled: { type: "boolean", description: "Whether two-factor authentication should be enabled or disabled" }
},
required: ["email", "enabled"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully updated two-factor authentication status",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { type: "boolean" },
message: { type: "string" }
}
}
}
}
},
'422': {
description: "Invalid email or user not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { type: "boolean" },
error_message: { type: "string" }
}
}
}
}
}
}
}.freeze
def update_two_factor_authentication_enabled
if params[:email].blank?
return render json: { success: false, error_message: "Email is required." }, status: :unprocessable_entity
end
if params[:enabled].nil?
return render json: { success: false, error_message: "Enabled status is required." }, status: :unprocessable_entity
end
user = User.alive.by_email(params[:email]).first
if user.present?
user.two_factor_authentication_enabled = params[:enabled]
if user.save
render json: { success: true, message: "Two-factor authentication #{user.two_factor_authentication_enabled? ? "enabled" : "disabled"}." }
else
render json: { success: false, error_message: user.errors.full_messages.join(", ") }, status: :unprocessable_entity
end
else
render json: { success: false, error_message: "An account does not exist with that email." }, status: :unprocessable_entity
end
end
CREATE_USER_APPEAL_OPENAPI = {
summary: "Create user appeal",
description: "Create an appeal for a suspended user who believes they have been suspended in error",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
email: { type: "string", description: "Email address of the user" },
reason: { type: "string", description: "Reason for the appeal" }
},
required: ["email", "reason"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully created appeal",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
id: { type: "string", description: "ID of the appeal" },
appeal_url: { type: "string", description: "URL for the user to view their appeal" }
}
}
}
}
},
'400': {
description: "Invalid parameters",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
error_message: { type: "string" }
}
}
}
}
},
'422': {
description: "User not found or appeal creation failed",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
error_message: { type: "string" }
}
}
}
}
}
}
}.freeze
def create_appeal
if params[:email].blank?
return render json: { success: false, error_message: "'email' parameter is required" }, status: :bad_request
end
if params[:reason].blank?
return render json: { success: false, error_message: "'reason' parameter is required" }, status: :bad_request
end
user = User.alive.by_email(params[:email]).first
if user.blank?
return render json: { success: false, error_message: "An account does not exist with that email." }, status: :unprocessable_entity
end
iffy_url = Rails.env.production? ? "https://api.iffy.com/api/v1" : "http://localhost:3000/api/v1"
begin
response = HTTParty.get(
"#{iffy_url}/users?email=#{CGI.escape(params[:email])}",
headers: {
"Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}"
}
)
if !(response.success? && response.parsed_response["data"].present? && !response.parsed_response["data"].empty?)
error_message = response.parsed_response.is_a?(Hash) ? response.parsed_response["error"]&.[]("message") || "Failed to find user" : "Failed to find user"
return render json: { success: false, error_message: error_message }, status: :unprocessable_entity
end
user_data = response.parsed_response["data"].first
user_id = user_data["id"]
response = HTTParty.post(
"#{iffy_url}/users/#{user_id}/create_appeal",
headers: {
"Authorization" => "Bearer #{GlobalConfig.get("IFFY_API_KEY")}",
"Content-Type" => "application/json"
},
body: {
text: params[:reason]
}.to_json
)
if !(response.success? && response.parsed_response["data"].present? && !response.parsed_response["data"].empty?)
error_message = response.parsed_response.dig("error", "message") || "Failed to create appeal"
return render json: { success: false, error_message: }, status: :unprocessable_entity
end
appeal_data = response.parsed_response["data"]
appeal_id = appeal_data["id"]
appeal_url = appeal_data["appealUrl"]
render json: {
success: true,
id: appeal_id,
appeal_url: appeal_url
}
rescue HTTParty::Error, Net::OpenTimeout, Net::ReadTimeout, Timeout::Error, Errno::ECONNREFUSED, SocketError => e
Bugsnag.notify(e)
render json: {
success: false,
error_message: "Failed to create appeal"
}, status: :service_unavailable
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/helper/webhook_controller.rb | app/controllers/api/internal/helper/webhook_controller.rb | # frozen_string_literal: true
class Api::Internal::Helper::WebhookController < Api::Internal::Helper::BaseController
skip_before_action :authorize_helper_token!
before_action :authorize_hmac_signature!
before_action :require_params!
def handle
event = params[:event]
payload = params[:payload]
Rails.logger.info("Incoming Helper (conversation). event: #{event}, conversation_id: #{payload["conversation_id"]}")
HandleHelperEventWorker.perform_async(event, payload.as_json)
render json: { success: true }
end
private
def require_params!
render json: { success: false, error: "missing required parameters" }, status: :bad_request if params[:event].blank? || params[:payload].blank?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/helper/base_controller.rb | app/controllers/api/internal/helper/base_controller.rb | # frozen_string_literal: true
class Api::Internal::Helper::BaseController < Api::Internal::BaseController
skip_before_action :verify_authenticity_token
before_action :verify_authorization_header!
before_action :authorize_helper_token!
HMAC_EXPIRATION = 1.minute
private
def authorize_hmac_signature!
json = request.body.read.empty? ? nil : JSON.parse(request.body.read)
query_params = json ? nil : request.query_parameters
timestamp = json ? json.dig("timestamp") : query_params[:timestamp]
return render json: { success: false, message: "timestamp is required" }, status: :bad_request if timestamp.blank?
if (Time.at(timestamp.to_i) - Time.now).abs > HMAC_EXPIRATION
return render json: { success: false, message: "bad timestamp" }, status: :unauthorized
end
hmac_digest = Base64.decode64(request.authorization.split(" ").last)
expected_digest = Helper::Client.new.create_hmac_digest(params: query_params, json:)
unless ActiveSupport::SecurityUtils.secure_compare(hmac_digest, expected_digest)
render json: { success: false, message: "authorization is invalid" }, status: :unauthorized
end
end
def authorize_helper_token!
token = request.authorization.split(" ").last
unless ActiveSupport::SecurityUtils.secure_compare(token, GlobalConfig.get("HELPER_TOOLS_TOKEN"))
render json: { success: false, message: "authorization is invalid" }, status: :unauthorized
end
end
def verify_authorization_header!
render json: { success: false, message: "unauthenticated" }, status: :unauthorized if request.authorization.nil?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/helper/openapi_controller.rb | app/controllers/api/internal/helper/openapi_controller.rb | # frozen_string_literal: true
class Api::Internal::Helper::OpenapiController < Api::Internal::Helper::BaseController
def index
render json: {
openapi: "3.1.0",
info: {
title: "Helper Tools API",
description: "API for Gumroad's Helper Tools",
version: "v1",
},
servers: [
{
url: "https://#{API_DOMAIN}/internal/helper",
description: "Production",
},
],
components: {
securitySchemes: {
bearer: {
type: :http,
scheme: "bearer",
},
},
},
paths: {
"/users/create_appeal": {
post: Api::Internal::Helper::UsersController::CREATE_USER_APPEAL_OPENAPI,
},
"/users/send_reset_password_instructions": {
post: Api::Internal::Helper::UsersController::SEND_RESET_PASSWORD_INSTRUCTIONS_OPENAPI,
},
"/users/update_email": {
post: Api::Internal::Helper::UsersController::UPDATE_EMAIL_OPENAPI,
},
"/users/update_two_factor_authentication_enabled": {
post: Api::Internal::Helper::UsersController::UPDATE_TWO_FACTOR_AUTHENTICATION_ENABLED_OPENAPI,
},
"/users/user_suspension_info": {
post: Api::Internal::Helper::UsersController::USER_SUSPENSION_INFO_OPENAPI,
},
"/purchases/refund_last_purchase": {
post: Api::Internal::Helper::PurchasesController::REFUND_LAST_PURCHASE_OPENAPI,
},
"/purchases/resend_last_receipt": {
post: Api::Internal::Helper::PurchasesController::RESEND_LAST_RECEIPT_OPENAPI,
},
"/purchases/resend_all_receipts": {
post: Api::Internal::Helper::PurchasesController::RESEND_ALL_RECEIPTS_OPENAPI,
},
"/purchases/resend_receipt_by_number": {
post: Api::Internal::Helper::PurchasesController::RESEND_RECEIPT_BY_NUMBER_OPENAPI,
},
"/purchases/search": {
post: Api::Internal::Helper::PurchasesController::SEARCH_PURCHASE_OPENAPI,
},
"/purchases/refresh_library": {
post: Api::Internal::Helper::PurchasesController::REFRESH_LIBRARY_OPENAPI,
},
"/purchases/reassign_purchases": {
post: Api::Internal::Helper::PurchasesController::REASSIGN_PURCHASES_OPENAPI,
},
"/purchases/auto_refund_purchase": {
post: Api::Internal::Helper::PurchasesController::AUTO_REFUND_PURCHASE_OPENAPI,
},
"/purchases/refund_taxes_only": {
post: Api::Internal::Helper::PurchasesController::REFUND_TAXES_ONLY_OPENAPI,
},
"/payouts": {
post: Api::Internal::Helper::PayoutsController::CREATE_PAYOUT_OPENAPI,
get: Api::Internal::Helper::PayoutsController::PAYOUT_INDEX_OPENAPI,
},
"/instant_payouts": {
post: Api::Internal::Helper::InstantPayoutsController::CREATE_INSTANT_PAYOUT_OPENAPI,
get: Api::Internal::Helper::InstantPayoutsController::INSTANT_PAYOUT_BALANCE_OPENAPI,
}
},
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/helper/payouts_controller.rb | app/controllers/api/internal/helper/payouts_controller.rb | # frozen_string_literal: true
class Api::Internal::Helper::PayoutsController < Api::Internal::Helper::BaseController
before_action :fetch_user
PAYOUT_INDEX_OPENAPI = {
summary: "Get payout information",
description: "Get last 5 payouts details, next payout date and balance for next payout date",
parameters: [
{
name: "email",
in: "query",
required: true,
schema: {
type: "string"
},
description: "Email address of the seller"
}
],
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully retrieved payout information",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
last_payouts: {
type: "array",
items: {
type: "object",
properties: {
external_id: { type: "string" },
amount_cents: { type: "integer" },
currency: { type: "string" },
state: { type: "string" },
created_at: { type: "string", format: "date-time" },
processor: { type: "string" },
bank_account_visual: { type: "string" },
paypal_email: { type: "string" }
},
required: ["external_id", "amount_cents", "currency", "state", "created_at", "processor"]
}
},
next_payout_date: { type: "string", format: "date" },
balance_for_next_payout: { type: "string" },
payout_note: { type: ["string", "null"] }
},
required: ["success", "last_payouts", "next_payout_date", "balance_for_next_payout", "payout_note"]
}
}
}
},
'404': {
description: "User not found",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
}
}
}.freeze
def index
payouts = @user.payments.order(created_at: :desc).limit(5).map do |payment|
{
external_id: payment.external_id,
amount_cents: payment.amount_cents,
currency: payment.currency,
state: payment.state,
created_at: payment.created_at,
processor: payment.processor,
bank_account_visual: payment.bank_account&.account_number_visual,
paypal_email: payment.payment_address
}
end
next_payout_date = @user.next_payout_date
balance_for_next_payout = @user.formatted_balance_for_next_payout_date
payout_note = @user.comments.with_type_payout_note.where(author_id: GUMROAD_ADMIN_ID).last&.content
render json: { success: true, last_payouts: payouts, next_payout_date:, balance_for_next_payout:, payout_note: }
end
CREATE_PAYOUT_OPENAPI = {
summary: "Create new payout",
description: "Create a new payout for a user, checking if eligible and after the last successful payout was more than a week ago",
requestBody: {
required: true,
content: {
'application/json': {
schema: {
type: "object",
properties: {
email: { type: "string", description: "Email address of the seller" }
},
required: ["email"]
}
}
}
},
security: [{ bearer: [] }],
responses: {
'200': {
description: "Successfully created payout",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: true },
message: { type: "string" },
payout: {
type: "object",
properties: {
external_id: { type: "string" },
amount_cents: { type: "integer" },
currency: { type: "string" },
state: { type: "string" },
created_at: { type: "string", format: "date-time" },
processor: { type: "string" },
bank_account_visual: { type: "string" },
paypal_email: { type: "string" }
},
required: ["external_id", "amount_cents", "currency", "state", "created_at", "processor"]
}
},
required: ["success", "message", "payout"]
}
}
}
},
'422': {
description: "Unable to create payout",
content: {
'application/json': {
schema: {
type: "object",
properties: {
success: { const: false },
message: { type: "string" }
}
}
}
}
}
}
}.freeze
def create
payout_date = User::PayoutSchedule.manual_payout_end_date
payout_processor_type = if @user.active_bank_account.present?
PayoutProcessorType::STRIPE
elsif @user.paypal_payout_email.present?
PayoutProcessorType::PAYPAL
else
nil
end
if payout_processor_type.blank?
render json: {
success: false,
message: "Cannot create payout. Payout method not set up."
}, status: :unprocessable_entity
return
end
last_successful_payout = @user.payments.completed.order(created_at: :desc).first
if last_successful_payout && last_successful_payout.created_at > 1.week.ago
render json: {
success: false,
message: "Cannot create payout. Last successful payout was less than a week ago."
}, status: :unprocessable_entity
return
end
if Payouts.is_user_payable(@user, payout_date, processor_type: payout_processor_type, add_comment: true)
payments = PayoutUsersService.new(date_string: payout_date,
processor_type: payout_processor_type,
user_ids: [@user.id]).process
payment = payments.first
if payment&.persisted? && (payment.processing? || payment.completed?)
render json: {
success: true,
message: "Successfully created payout",
payout: {
external_id: payment.external_id,
amount_cents: payment.amount_cents,
currency: payment.currency,
state: payment.state,
created_at: payment.created_at,
processor: payment.processor,
bank_account_visual: payment.bank_account&.account_number_visual,
paypal_email: payment.payment_address,
}
}
else
error_message = payment&.errors&.full_messages&.to_sentence || "Unable to create payout"
render json: { success: false, message: error_message }, status: :unprocessable_entity
end
else
payout_note = @user.reload.comments.with_type_payout_note.where(author_id: GUMROAD_ADMIN_ID).last&.content
payout_note&.gsub!("via #{payout_processor_type.capitalize} on #{payout_date.to_fs(:formatted_date_full_month)} ", "")
message = "User is not eligible for payout."
message += " #{payout_note}" if payout_note.present?
render json: { success: false, message: }, status: :unprocessable_entity
end
end
private
def fetch_user
if params[:email].blank?
render json: { success: false, message: "Email is required" }, status: :unprocessable_entity
return
end
@user = User.alive.by_email(params[:email]).first
render json: { success: false, message: "User not found" }, status: :not_found unless @user
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/iffy/webhook_controller.rb | app/controllers/api/internal/iffy/webhook_controller.rb | # frozen_string_literal: true
class Api::Internal::Iffy::WebhookController < Api::Internal::BaseController
skip_before_action :verify_authenticity_token
before_action :authorize_hmac_signature!
HMAC_EXPIRATION = 1.minute
def handle
event = params.require(:event)
payload = params.require(:payload).permit(:clientId, :entity, user: [:protected])
user_data = payload[:user]&.as_json if payload[:user].present?
Iffy::EventJob.perform_async(
event,
payload[:clientId],
payload[:entity],
user_data
)
head :ok
end
private
def authorize_hmac_signature!
timestamp = params.require(:timestamp).to_i
return render json: { success: false, message: "timestamp is required" }, status: :bad_request if timestamp.blank?
signature = request.headers["HTTP_X_SIGNATURE"]
return render json: { success: false, message: "signature is required" }, status: :unauthorized if signature.blank?
if (timestamp / 1000.0 - Time.now.to_f).abs > HMAC_EXPIRATION
return render json: { success: false, message: "bad timestamp" }, status: :unauthorized
end
body = request.body.read
expected_signature = OpenSSL::HMAC.hexdigest("sha256", GlobalConfig.get("IFFY_WEBHOOK_SECRET"), body)
unless ActiveSupport::SecurityUtils.secure_compare(signature, expected_signature)
render json: { success: false, message: "signature is invalid" }, status: :unauthorized
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/product_review_videos/approvals_controller.rb | app/controllers/api/internal/product_review_videos/approvals_controller.rb | # frozen_string_literal: true
class Api::Internal::ProductReviewVideos::ApprovalsController < Api::Internal::BaseController
before_action :authenticate_user!
before_action :set_product_review_video!
after_action :verify_authorized
def create
authorize @product_review_video, :approve?
@product_review_video.approved!
head :ok
end
private
def set_product_review_video!
@product_review_video = ProductReviewVideo.alive
.find_by_external_id!(params[:product_review_video_id])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/product_review_videos/rejections_controller.rb | app/controllers/api/internal/product_review_videos/rejections_controller.rb | # frozen_string_literal: true
class Api::Internal::ProductReviewVideos::RejectionsController < Api::Internal::BaseController
before_action :authenticate_user!
before_action :set_product_review_video!
after_action :verify_authorized
def create
authorize @product_review_video, :reject?
@product_review_video.rejected!
head :ok
end
private
def set_product_review_video!
@product_review_video = ProductReviewVideo.alive
.find_by_external_id!(params[:product_review_video_id])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/internal/grmc/webhook_controller.rb | app/controllers/api/internal/grmc/webhook_controller.rb | # frozen_string_literal: true
class Api::Internal::Grmc::WebhookController < Api::Internal::BaseController
skip_before_action :verify_authenticity_token
before_action :authorize_hmac_signature!
def handle
HandleGrmcCallbackJob.perform_async(JSON.parse(request.body.read))
head :ok
end
private
def authorize_hmac_signature!
timestamp, signature = request.headers["HTTP_GRMC_SIGNATURE"].to_s.scan(/([^,=]+)=([^,=]+)/).to_h.slice("t", "v0").values
if (timestamp.to_i / 1000.0 - Time.current.to_f).abs <= 1.minute
expected_signature = OpenSSL::HMAC.hexdigest("sha256", GlobalConfig.get("GRMC_WEBHOOK_SECRET"), request.body.read)
return true if ActiveSupport::SecurityUtils.secure_compare(signature.to_s, expected_signature)
end
render json: { success: false, message: "invalid timestamp or signature" }, status: :unauthorized
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/custom_fields_controller.rb | app/controllers/api/v2/custom_fields_controller.rb | # frozen_string_literal: true
class Api::V2::CustomFieldsController < Api::V2::BaseController
before_action(only: [:index]) { doorkeeper_authorize!(*Doorkeeper.configuration.public_scopes.concat([:view_public])) }
before_action(only: [:create, :update, :destroy]) { doorkeeper_authorize! :edit_products }
before_action :fetch_product
before_action :fetch_custom_fields
before_action :fetch_custom_field, only: %i[update destroy]
# no whitelist here because custom fields are weird
def index
success_with_object(:custom_fields, @custom_fields)
end
def create
custom_field_name = params[:name].presence || params[:url].presence || params[:label].presence
return error_with_creating_object(:custom_field) if custom_field_name.blank?
new_custom_field = {
name: custom_field_name,
required: params[:required] == "true",
type: params[:type] || "text"
}
field = @product.user.custom_fields.new(new_custom_field.merge({ products: [@product] }))
if field.save
success_with_custom_field(field)
else
error_with_creating_object(:custom_field)
end
end
def update
if params[:required].nil?
# nothing to change, so we succeeded in changing nothing!
success_with_custom_field(@custom_field)
else
@custom_field.update(required: params[:required] == "true")
if @product.update(custom_fields: @custom_fields)
success_with_custom_field(@custom_field)
else
error_with_custom_field(@custom_field)
end
end
end
def destroy
if @custom_field.products.count > 1 ? @custom_field.products.delete(@product) : @custom_field.delete
success_with_custom_field
else
error_with_object(:custom_fields, @custom_fields)
end
end
private
def fetch_custom_fields
@custom_fields = @product.custom_fields
end
def fetch_custom_field
@custom_field = @custom_fields.where(name: params[:id]).last
error_with_custom_field if @custom_field.nil?
end
def success_with_custom_field(custom_field = nil)
success_with_object(:custom_field, custom_field)
end
def error_with_custom_field(custom_field = nil)
error_with_object(:custom_field, custom_field)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/licenses_controller.rb | app/controllers/api/v2/licenses_controller.rb | # frozen_string_literal: true
class Api::V2::LicensesController < Api::V2::BaseController
before_action :log_params, only: [:verify]
before_action :clean_params, only: [:verify]
before_action(only: [:enable, :disable, :decrement_uses_count, :rotate]) { doorkeeper_authorize! :edit_products }
before_action :fetch_valid_license
before_action :validate_license_user, only: [:enable, :disable, :decrement_uses_count, :rotate]
skip_before_action :verify_authenticity_token, only: [:verify]
# Purchase values we want to include for license API responses
WHITELIST_PURCHASE_ATTRIBUTES = %i[id created_at variants custom_fields offer_code refunded chargebacked
subscription_ended_at subscription_cancelled_at subscription_failed_at].freeze
RAISE_ERROR_ON_PRODUCT_PERMALINK_PARAM_AFTER = 30.days
PRODUCT_PERMALINK_SELLER_NOTIFICATION_INTERVAL = 5.days
private_constant :PRODUCT_PERMALINK_SELLER_NOTIFICATION_INTERVAL
def enable
@license.enable!
success_with_license
end
def disable
@license.disable!
success_with_license
end
def rotate
@license.rotate!
success_with_license
end
def verify
return render json: { success: false, message: "This license key has been disabled." }, status: :not_found if @license.disabled?
update_license_uses
success_with_license
end
def decrement_uses_count
@license.with_lock do
@license.decrement!(:uses) if @license.uses > 0
end
success_with_license
end
private
def validate_license_user
e404_json if @license.link.user != current_resource_owner
end
def update_license_uses
@license.increment!(:uses) if params[:increment_uses_count]
end
def fetch_valid_license
if params[:product_id].present?
product = Link.find_by_external_id(params[:product_id])
@license = product.licenses.find_by(serial: params[:license_key]) if product.present?
else
@license = License.find_by(serial: params[:license_key])
product = @license&.link
end
# Force sellers to use product_id param in license verification request
if params[:product_id].blank? \
&& product.present? \
&& !skip_product_id_check(product)
# Raise HTTP 500 if the product is created on or after a specific date
if force_product_id_timestamp.present? && product.created_at > force_product_id_timestamp
Rails.logger.error("[License Verification Error] product_id missing, responding with HTTP 500 for product: #{product.id}")
message = "The 'product_id' parameter is required to verify the license for this product. "
message += "Please set 'product_id' to '#{@license.link.external_id}' in the request."
return render json: { success: false, message: }, status: :internal_server_error
end
end
# Skip verifying product_permalink when product_id is present
if @license.blank? || (params[:product_id].blank? && !product.matches_permalink?(params[:product_permalink]))
message = "That license does not exist for the provided product."
render json: { success: false, message: }, status: :not_found
elsif @license.purchase&.is_access_revoked?
message = "Access to the purchase associated with this license has expired."
render json: { success: false, message: }, status: :not_found
end
end
def success_with_license
Rails.logger.info("License information for #{@license.serial} , license.purchase: #{@license.purchase&.id} , license.imported_customer: #{@license.imported_customer&.id}")
json = { success: true }.merge(@license.as_json(only: [:uses]))
if @license.purchase.present?
purchase = @license.purchase
json[:purchase] = purchase.payload_for_ping_notification.merge(purchase_as_json(purchase))
elsif @license.imported_customer.present?
json[:imported_customer] = @license.imported_customer.as_json(without_license_key: true)
end
render json:
end
def clean_params
# `link_id` and `id` are legacy ways to pass in the product's permalink, no longer documented but used in the wild
# The order of these parameters matters to properly support legacy requests!
params[:product_permalink] = params[:id].presence || params[:link_id].presence || params[:product_permalink].presence
params[:increment_uses_count] = ["false", false].exclude?(params[:increment_uses_count])
end
def purchase_as_json(purchase)
json = purchase.as_json_for_license
json.keep_if { |key, _| WHITELIST_PURCHASE_ATTRIBUTES.include? key }
json
end
# Temporary debug output
def log_params
logger.info "Verify license API request: #{params.inspect}"
end
def redis_namespace
@_redis_namespace ||= Redis::Namespace.new(:license_verifications, redis: $redis)
end
def skip_product_id_check(product)
redis_namespace.get("skip_product_id_check_#{product.id}").present?
end
def force_product_id_timestamp
@_force_prouct_id_timestamp ||= $redis.get(RedisKey.force_product_id_timestamp)&.to_datetime
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/skus_controller.rb | app/controllers/api/v2/skus_controller.rb | # frozen_string_literal: true
class Api::V2::SkusController < Api::V2::BaseController
before_action -> { doorkeeper_authorize!(*Doorkeeper.configuration.public_scopes.concat([:view_public])) }
before_action :fetch_product
def index
skus = if @product.skus_enabled?
@product.skus.alive.not_is_default_sku.exists? ? @product.skus.alive.not_is_default_sku : @product.skus.alive.is_default_sku
elsif @product.is_physical?
@product.alive_variants
else
[]
end
success_with_object(:skus, skus)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/variant_categories_controller.rb | app/controllers/api/v2/variant_categories_controller.rb | # frozen_string_literal: true
class Api::V2::VariantCategoriesController < Api::V2::BaseController
before_action(only: [:index, :show]) { doorkeeper_authorize!(*Doorkeeper.configuration.public_scopes.concat([:view_public])) }
before_action(only: [:create, :update, :destroy]) { doorkeeper_authorize! :edit_products }
before_action :fetch_product
before_action :fetch_variant_category, only: [:show, :update, :destroy]
def index
success_with_object(:variant_categories, @product.variant_categories.alive)
end
def create
variant_category = VariantCategory.create(permitted_params.merge(link_id: @product.id))
success_with_variant_category(variant_category)
end
def show
success_with_variant_category(@variant_category)
end
def update
if @variant_category.update(permitted_params)
success_with_variant_category(@variant_category)
else
error_with_variant_category(@variant_category)
end
end
def destroy
if @variant_category.mark_deleted
success_with_variant_category
else
error_with_variant_category(@variant_category)
end
end
private
def permitted_params
params.permit(:title)
end
def fetch_variant_category
@variant_category = @product.variant_categories.find_by_external_id(params[:id])
error_with_variant_category if @variant_category.nil?
end
def success_with_variant_category(variant_category = nil)
success_with_object(:variant_category, variant_category)
end
def error_with_variant_category(variant_category = nil)
error_with_object(:variant_category, variant_category)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/links_controller.rb | app/controllers/api/v2/links_controller.rb | # frozen_string_literal: true
class Api::V2::LinksController < Api::V2::BaseController
before_action(only: [:show, :index]) { doorkeeper_authorize!(*Doorkeeper.configuration.public_scopes.concat([:view_public])) }
before_action(only: [:create, :update, :disable, :enable, :destroy]) { doorkeeper_authorize! :edit_products }
before_action :check_types_of_file_objects, only: [:update, :create]
before_action :set_link_id_to_id, only: [:show, :update, :disable, :enable, :destroy]
before_action :fetch_product, only: [:show, :update, :disable, :enable, :destroy]
def index
products = current_resource_owner.products.visible.includes(
:preorder_link, :tags, :taxonomy,
variant_categories_alive: [:alive_variants],
).order(created_at: :desc)
as_json_options = {
api_scopes: doorkeeper_token.scopes,
preloaded_ppp_factors: PurchasingPowerParityService.new.get_all_countries_factors(current_resource_owner)
}
products_as_json = products.as_json(as_json_options)
render json: { success: true, products: products_as_json }
end
def create
e404
end
def show
success_with_product(@product)
end
def update
e404
end
def disable
return success_with_product(@product) if @product.unpublish!
error_with_product(@product)
end
def enable
return error_with_product(@product) unless @product.validate_product_price_against_all_offer_codes?
begin
@product.publish!
rescue Link::LinkInvalid
return error_with_product(@product)
rescue => e
Bugsnag.notify(e)
return render_response(false, message: "Something broke. We're looking into what happened. Sorry about this!")
end
success_with_product(@product)
end
def destroy
success_with_product if @product.delete!
end
private
def success_with_product(product = nil)
success_with_object(:product, product)
end
def error_with_product(product = nil)
error_with_object(:product, product)
end
def check_types_of_file_objects
return if params[:file].class != String && params[:preview].class != String
render_response(false, message: "You entered the name of the file to be uploaded incorrectly. Please refer to " \
"https://gumroad.com/api#methods for the correct syntax.")
end
def set_link_id_to_id
params[:link_id] = params[:id]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/resource_subscriptions_controller.rb | app/controllers/api/v2/resource_subscriptions_controller.rb | # frozen_string_literal: true
class Api::V2::ResourceSubscriptionsController < Api::V2::BaseController
before_action(only: [:index, :create, :destroy]) { doorkeeper_authorize! :view_sales }
def index
resource_name = params[:resource_name]
if ResourceSubscription.valid_resource_name?(resource_name)
success_with_object(:resource_subscriptions, current_resource_owner.resource_subscriptions.alive.where(resource_name: params[:resource_name]))
else
render_response(false, message: "Valid resource_name parameter required")
end
end
def create
resource_name = params[:resource_name]
post_url = params[:post_url]
return error_with_post_url(post_url) unless ResourceSubscription.valid_post_url?(post_url)
if ResourceSubscription.valid_resource_name?(resource_name)
resource_subscription = ResourceSubscription.create!(
user: current_resource_owner,
oauth_application: OauthApplication.find(doorkeeper_token.application.id),
resource_name:,
post_url:
)
success_with_resource_subscription(resource_subscription)
else
error_with_subscription_resource(resource_subscription)
end
end
def destroy
resource_subscription = ResourceSubscription.find_by_external_id(params[:id])
if resource_subscription && doorkeeper_token.application_id == resource_subscription.oauth_application.id
resource_subscription.mark_deleted!
success_with_resource_subscription(nil)
else
error_with_object(:resource_subscription, nil)
end
end
def error_with_subscription_resource(resource_name)
render_response(false, message: "Unable to subscribe to '#{resource_name}'.")
end
def error_with_post_url(post_url)
render_response(false, message: "Invalid post URL '#{post_url}'")
end
def success_with_resource_subscription(resource_subscription)
success_with_object(:resource_subscription, resource_subscription)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/users_controller.rb | app/controllers/api/v2/users_controller.rb | # frozen_string_literal: true
class Api::V2::UsersController < Api::V2::BaseController
before_action -> { doorkeeper_authorize!(*Doorkeeper.configuration.public_scopes.concat([:view_public])) }, only: [:show, :ifttt_sale_trigger]
def show
if params[:is_ifttt]
user = current_resource_owner
user.name = current_resource_owner.email if user.name.blank?
return success_with_object(:data, user)
end
success_with_object(:user, current_resource_owner)
end
def ifttt_status
render json: { status: "success" }
end
def ifttt_sale_trigger
limit = params[:limit] || 50
sales = if params[:after].present?
current_resource_owner.sales.successful_or_preorder_authorization_successful.where(
"created_at >= ?", Time.zone.at(params[:after].to_i)
).order("created_at ASC").limit(limit)
elsif params[:before].present?
current_resource_owner.sales.successful_or_preorder_authorization_successful.where(
"created_at <= ?", Time.zone.at(params[:before].to_i)
).order("created_at DESC").limit(limit)
else
current_resource_owner.sales.successful_or_preorder_authorization_successful.order("created_at DESC").limit(limit)
end
sales = sales.map(&:as_json_for_ifttt)
success_with_object(:data, sales)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/subscribers_controller.rb | app/controllers/api/v2/subscribers_controller.rb | # frozen_string_literal: true
class Api::V2::SubscribersController < Api::V2::BaseController
before_action -> { doorkeeper_authorize!(:view_sales) }
before_action :fetch_product, only: :index
RESULTS_PER_PAGE = 100
def index
subscriptions = Subscription.where(link_id: @product.id).active
subscriptions = subscriptions.includes(:link, :purchases, last_payment_option: [:price]).order(created_at: :desc, id: :desc)
if params[:email].present?
email = params[:email].strip
subscriptions = subscriptions.where(purchases: { email: })
end
if params[:page_key].present?
begin
last_record_created_at, last_record_id = decode_page_key(params[:page_key])
rescue ArgumentError
return error_400("Invalid page_key.")
end
subscriptions = subscriptions.where("created_at <= ? and id < ?", last_record_created_at, last_record_id)
end
if params[:paginated].in?(["1", "true"]) || params[:page_key].present?
paginated_subscriptions = subscriptions.limit(RESULTS_PER_PAGE + 1).to_a
has_next_page = paginated_subscriptions.size > RESULTS_PER_PAGE
paginated_subscriptions = paginated_subscriptions.first(RESULTS_PER_PAGE)
additional_response = has_next_page ? pagination_info(paginated_subscriptions.last) : {}
success_with_object(:subscribers, paginated_subscriptions, additional_response)
else
success_with_object(:subscribers, subscriptions)
end
end
def show
subscription = Subscription.find_by_external_id(params[:id])
if subscription && subscription.link.user == current_resource_owner
success_with_subscription(subscription)
else
error_with_subscription
end
end
private
def success_with_subscription(subscription = nil)
success_with_object(:subscriber, subscription)
end
def error_with_subscription(subscription = nil)
error_with_object(:subscriber, subscription)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/notion_unfurl_urls_controller.rb | app/controllers/api/v2/notion_unfurl_urls_controller.rb | # frozen_string_literal: true
class Api::V2::NotionUnfurlUrlsController < Api::V2::BaseController
before_action(only: [:create]) { doorkeeper_authorize! :unfurl }
before_action :parse_uri, only: [:create]
before_action :fetch_product, only: [:create]
skip_before_action :verify_authenticity_token, only: [:create, :destroy]
def create
render_link_preview_payload
end
def destroy
head :ok
end
private
def parse_uri
return render_no_uri_error if params[:uri].blank?
@parsed_uri = Addressable::URI.parse(params[:uri])
return render_invalid_uri_error if @parsed_uri.host.blank?
@parsed_uri.query = nil
end
def fetch_product
seller = Subdomain.find_seller_by_hostname(@parsed_uri.host)
return render_invalid_uri_error if seller.blank? || !@parsed_uri.path.start_with?("/l/")
permalink = @parsed_uri.path.match(/\/l\/([\w-]+)/)&.captures&.first
return render_invalid_uri_error if permalink.blank?
@product = Link.fetch_leniently(permalink, user: seller)
render_invalid_uri_error if @product.blank?
end
def render_link_preview_payload
total_ratings = @product.rating_counts.values.sum
attributes = [
{
"id": "title",
"name": "Product name",
"inline": {
"title": {
"value": @product.name,
"section": "title"
}
}
},
{
"id": "creator_name",
"name": "Creator name",
"type": "inline",
"inline": {
"plain_text": {
"value": @product.user.display_name,
"section": "secondary",
}
}
},
{
"id": "rating",
"name": "Rating",
"type": "inline",
"inline": {
"plain_text": {
"value": %(★ #{@product.average_rating}#{total_ratings.zero? ? "" : " (#{pluralize(total_ratings, "rating")})"}),
"section": "secondary",
}
}
},
{
"id": "price",
"name": "Price",
"type": "inline",
"inline": {
"enum": {
"value": @product.price_formatted_including_rental_verbose,
"color": {
"r": 255,
"g": 144,
"b": 232
},
"section": "primary",
}
}
},
{
"id": "site",
"name": "Site",
"type": "inline",
"inline": {
"plain_text": {
"value": @parsed_uri.to_s,
"section": "secondary"
}
}
}
]
if @product.plaintext_description.present?
attributes << {
"id": "description",
"name": "Description",
"type": "inline",
"inline": {
"plain_text": {
"value": @product.plaintext_description.truncate(255),
"section": "body"
}
}
}
end
main_cover_image_url = @product.main_preview&.url
if main_cover_image_url.present?
attributes << {
"id": "media",
"name": "Embed",
"embed": {
"src_url": main_cover_image_url,
"image": { "section": "embed" }
}
}
end
render json: {
uri: params[:uri],
operations: [{ path: ["attributes"], set: attributes }]
}
end
def render_no_uri_error
render json: {
error: {
status: 404,
message: "Product not found"
}
}, status: :not_found
end
def render_invalid_uri_error
render json: {
uri: params[:uri],
operations: [{
path: ["error"],
set: { "status": 404, "message": "Product not found" }
}]
}, status: :not_found
end
def doorkeeper_unauthorized_render_options(**)
{
json: {
error: {
status: 401,
message: "Request need to be authorized. Required parameter for authorizing request is missing or invalid."
}
}
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/base_controller.rb | app/controllers/api/v2/base_controller.rb | # frozen_string_literal: true
class Api::V2::BaseController < ApplicationController
after_action :log_method_use
private
def fetch_product
products = current_resource_owner.links
@product = products.find_by_external_id(params[:link_id]) || products.find_by(unique_permalink: params[:link_id]) || error_with_object(:product, nil)
end
def render_response(success, result = {})
result = result.as_json(api_scopes: doorkeeper_token.scopes)
render json: { success: }.merge(result)
end
def current_resource_owner
User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token.present?
end
def success_with_object(object_type, object, additional_info = {})
if object.nil?
render_response(true, message: "The #{object_type} was deleted successfully.")
else
render_response(true, { object_type => object }.merge(additional_info))
end
end
# TODO we should return status code 404 Not Found when object is not found and 422 Unprocessable Entity when it's unable to be modified.
# There's a (small) chance this will break existing integrations, but should be improved in the next version of the API.
# https://gumroad.slack.com/archives/C5Z7LG6Q1/p1602496811465200
def error_with_object(object_name, object)
message = if object.present?
if object.respond_to?(:errors) && object.errors.present?
object.errors.full_messages.to_sentence
else
"The #{object_name} was unable to be modified."
end
else
"The #{object_name} was not found."
end
render_response(false, message:)
end
def error_with_creating_object(object_name, object = nil)
message = if object.present?
object.errors.full_messages.to_sentence
else
"The #{object_name} was unable to be created."
end
render_response(false, message:)
end
def error_400(error_output = "Invalid request.")
output = { status: 400, error: error_output }
render status: :bad_request, json: output
end
def log_method_use
return unless current_resource_owner.present?
return unless doorkeeper_token.present?
Rails.logger.info("api v2 user:#{current_resource_owner.id} token:#{doorkeeper_token.id} in #{params[:controller]}##{params[:action]}")
end
def next_page_url(page_key)
uri = Addressable::URI.parse(request.original_url)
uri.query_values = (uri.query_values || {}).except("access_token", "page", "page_key").merge(page_key:)
"#{uri.path}?#{uri.query}"
end
def encode_page_key(record)
record.created_at.to_fs(:usec) + "-" + ObfuscateIds.encrypt_numeric(record.id).to_s
end
def decode_page_key(string)
date_string, obfuscated_id = string.split("-")
last_record_obfuscated_id = obfuscated_id.to_i
raise ArgumentError if last_record_obfuscated_id == 0
[Time.zone.parse(date_string.gsub(/(\d{6})\z/, '.\1')), ObfuscateIds.decrypt_numeric(last_record_obfuscated_id).to_i]
end
def pagination_info(record)
next_page_key = encode_page_key(record)
{
next_page_key:,
next_page_url: next_page_url(next_page_key)
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/sales_controller.rb | app/controllers/api/v2/sales_controller.rb | # frozen_string_literal: true
class Api::V2::SalesController < Api::V2::BaseController
before_action(only: [:index, :show]) { doorkeeper_authorize! :view_sales }
before_action(only: [:mark_as_shipped]) { doorkeeper_authorize! :mark_sales_as_shipped }
before_action(only: [:refund]) { doorkeeper_authorize! :refund_sales, :edit_sales }
before_action(only: [:resend_receipt]) { doorkeeper_authorize! :edit_sales }
before_action :set_page, only: :index
RESULTS_PER_PAGE = 10
def index
begin
end_date = Date.strptime(params[:before], "%Y-%m-%d") if params[:before]
rescue ArgumentError
return error_400("Invalid date format provided in field 'before'. Dates must be in the format YYYY-MM-DD.")
end
begin
start_date = Date.strptime(params[:after], "%Y-%m-%d") if params[:after]
rescue ArgumentError
return error_400("Invalid date format provided in field 'after'. Dates must be in the format YYYY-MM-DD.")
end
email = params[:email].present? ? params[:email].strip : nil
if params[:product_id].present?
product_id = ObfuscateIds.decrypt(params[:product_id])
# The de-obfuscation above will fail silently if invalid base64 string is passed.
# Here, the user is clearly trying to scope their results to a single product,
# so we cannot proceed with product_id = nil, or we will return a wider than expected result set.
return error_400("Invalid product ID.") if product_id.nil?
end
if params[:order_id].present?
return error_400("Invalid order ID.") if params[:order_id].to_i.to_s != params[:order_id]
purchase_id = ObfuscateIds.decrypt_numeric(params[:order_id].to_i)
end
if params[:page] # DEPRECATED
filtered_sales = filter_sales(start_date:, end_date:, email:, product_id:, purchase_id:, root_scope: current_resource_owner.sales)
begin
timeout_s = ($redis.get(RedisKey.api_v2_sales_deprecated_pagination_query_timeout) || 15).to_i
WithMaxExecutionTime.timeout_queries(seconds: timeout_s) do
paginated_sales = filtered_sales.for_sales_api.limit(RESULTS_PER_PAGE + 1).offset((@page - 1) * RESULTS_PER_PAGE).to_a
has_next_page = paginated_sales.size > RESULTS_PER_PAGE
paginated_sales = paginated_sales.first(RESULTS_PER_PAGE)
if has_next_page
success_with_object(:sales, paginated_sales.as_json(version: 2), pagination_info(paginated_sales.last))
else
success_with_object(:sales, paginated_sales.as_json(version: 2))
end
end
rescue WithMaxExecutionTime::QueryTimeoutError
error_400("The 'page' parameter is deprecated. Please use 'page_key' instead: https://gumroad.com/api#sales")
end
return
end
if params[:page_key].present?
begin
last_purchase_created_at, last_purchase_id = decode_page_key(params[:page_key])
rescue ArgumentError
return error_400("Invalid page_key.")
end
where_page_data = ["created_at <= ? and id < ?", last_purchase_created_at, last_purchase_id]
end
paginated_sales = filter_sales(start_date:, end_date:, email:, product_id:, purchase_id:)
subquery_filters = ->(query) {
query.where(seller_id: current_resource_owner.id).where(where_page_data).order(created_at: :desc, id: :desc).limit(RESULTS_PER_PAGE + 1)
}
paginated_sales = paginated_sales.for_sales_api_ordered_by_date(subquery_filters)
paginated_sales = paginated_sales.limit(RESULTS_PER_PAGE + 1).to_a
has_next_page = paginated_sales.size > RESULTS_PER_PAGE
paginated_sales = paginated_sales.first(RESULTS_PER_PAGE)
additional_response = has_next_page ? pagination_info(paginated_sales.last) : {}
success_with_object(:sales, paginated_sales.as_json(version: 2), additional_response)
end
def show
purchase = current_resource_owner.sales.find_by_external_id(params[:id])
purchase ? success_with_sale(purchase.as_json(version: 2)) : error_with_sale
end
def mark_as_shipped
purchase = current_resource_owner.sales.find_by_external_id(params[:id])
return error_with_sale if purchase.nil?
shipment = Shipment.create(purchase:) if purchase.shipment.blank?
shipment ||= purchase.shipment
if params[:tracking_url]
shipment.tracking_url = params[:tracking_url]
shipment.save!
end
shipment.mark_shipped
success_with_sale(purchase.as_json(version: 2))
end
def refund
purchase = current_resource_owner.sales.find_by_external_id(params[:id])
return error_with_sale if purchase.nil?
if purchase.refunded?
purchase.errors.add(:base, "Purchase is already refunded.")
return error_with_sale(purchase)
end
amount = params[:amount_cents].to_i / 100.0 if params[:amount_cents].present?
if purchase.refund!(refunding_user_id: current_resource_owner.id, amount:)
success_with_sale(purchase.as_json(version: 2))
else
error_with_sale(purchase)
end
end
def resend_receipt
purchase = current_resource_owner.sales.find_by_external_id(params[:id])
return error_with_sale if purchase.nil?
purchase.resend_receipt
render_response(true)
end
private
def success_with_sale(sale = nil)
success_with_object(:sale, sale)
end
def error_with_sale(sale = nil)
error_with_object(:sale, sale)
end
def filter_sales(start_date:, end_date:, email:, product_id:, purchase_id:, root_scope: Purchase)
sales = root_scope
sales = sales.where("created_at >= ?", start_date) if start_date
sales = sales.where("created_at < ?", end_date) if end_date
sales = sales.where(email:) if email.present?
sales = sales.where(link_id: product_id) if product_id.present?
sales = sales.where(id: purchase_id) if purchase_id.present?
sales.order(created_at: :desc, id: :desc)
end
def set_page # DEPRECATED
@page = (params[:page] || 1).to_i
error_400("Invalid page number. Page numbers start at 1.") unless @page > 0
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/payouts_controller.rb | app/controllers/api/v2/payouts_controller.rb | # frozen_string_literal: true
class Api::V2::PayoutsController < Api::V2::BaseController
include PayoutsHelper
before_action -> { doorkeeper_authorize!(:view_payouts) }
RESULTS_PER_PAGE = 10
def index
begin
end_date = Date.strptime(params[:before], "%Y-%m-%d") if params[:before]
rescue ArgumentError
return error_400("Invalid date format provided in field 'before'. Dates must be in the format YYYY-MM-DD.")
end
begin
start_date = Date.strptime(params[:after], "%Y-%m-%d") if params[:after]
rescue ArgumentError
return error_400("Invalid date format provided in field 'after'. Dates must be in the format YYYY-MM-DD.")
end
if params[:page_key].present?
begin
last_payout_created_at, last_payout_id = decode_page_key(params[:page_key])
rescue ArgumentError
return error_400("Invalid page_key.")
end
where_page_data = ["(created_at < ?) OR (created_at = ? AND id < ?)", last_payout_created_at, last_payout_created_at, last_payout_id]
end
paginated_payouts = filter_payouts(start_date: start_date, end_date: end_date)
paginated_payouts = paginated_payouts.where(where_page_data) if where_page_data
paginated_payouts = paginated_payouts.limit(RESULTS_PER_PAGE + 1).to_a
if params[:page_key].blank? && params[:include_upcoming] != "false"
current_resource_owner.upcoming_payout_amounts.filter { end_date.nil? || end_date >= _1 }.each do |payout_date, payout_amount|
paginated_payouts.unshift(
Payment.new(
amount_cents: payout_amount,
currency: Currency::USD,
state: current_resource_owner.payouts_status,
created_at: payout_date,
processor: current_resource_owner.current_payout_processor,
bank_account: (current_resource_owner.active_bank_account if current_resource_owner.current_payout_processor == PayoutProcessorType::STRIPE),
payment_address: (current_resource_owner.paypal_payout_email if current_resource_owner.current_payout_processor == PayoutProcessorType::PAYPAL),
).as_json.merge(id: nil)
)
end
end
has_next_page = paginated_payouts.size > RESULTS_PER_PAGE
paginated_payouts = paginated_payouts.first(RESULTS_PER_PAGE)
additional_response = has_next_page ? pagination_info(paginated_payouts.last) : {}
success_with_object(:payouts, paginated_payouts.as_json, additional_response)
end
def show
payout = current_resource_owner.payments.find_by_external_id(params[:id])
if payout
include_sales = doorkeeper_token.scopes.include?("view_sales")
success_with_payout(payout.as_json(include_sales: include_sales))
else
error_with_payout
end
end
private
def success_with_payout(payout = nil)
success_with_object(:payout, payout)
end
def error_with_payout(payout = nil)
error_with_object(:payout, payout)
end
def filter_payouts(start_date:, end_date:)
payouts = current_resource_owner.payments.displayable
payouts = payouts.where("created_at >= ?", start_date) if start_date
payouts = payouts.where("created_at < ?", end_date) if end_date
payouts.order(created_at: :desc, id: :desc)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/variants_controller.rb | app/controllers/api/v2/variants_controller.rb | # frozen_string_literal: true
class Api::V2::VariantsController < Api::V2::BaseController
before_action(only: [:index, :show]) { doorkeeper_authorize!(*Doorkeeper.configuration.public_scopes.concat([:view_public])) }
before_action(only: [:create, :update, :destroy]) { doorkeeper_authorize! :edit_products }
before_action :fetch_product
before_action :fetch_variant_category, only: [:index, :create, :show, :update, :destroy]
before_action :fetch_variant, only: [:show, :update, :destroy]
def index
success_with_object(:variants, @variants.alive)
end
def create
variant = Variant.new(permitted_params)
variant.variant_category = @variant_category
if variant.save
success_with_variant(variant)
else
error_with_creating_object(:variant, variant)
end
end
def show
success_with_variant(@variant)
end
def update
if @variant.update(permitted_params)
success_with_variant(@variant)
else
error_with_variant(@variant)
end
end
def destroy
if @variant.update_attribute(:deleted_at, Time.current)
success_with_variant
else
error_with_variant
end
end
private
def permitted_params
params.permit(:price_difference_cents, :description, :name, :max_purchase_count)
end
def fetch_variant
@variant = @variants.find_by_external_id(params[:id])
error_with_variant(@variant) if @variant.nil?
end
def fetch_variant_category
@variant_category = @product.variant_categories.find_by_external_id(params[:variant_category_id])
@variants = @variant_category.variants
error_with_object(:variant_category) if @variant_category.nil?
end
def success_with_variant(variant = nil)
success_with_object(:variant, variant)
end
def error_with_variant(variant = nil)
error_with_object(:variant, variant)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/api/v2/offer_codes_controller.rb | app/controllers/api/v2/offer_codes_controller.rb | # frozen_string_literal: true
class Api::V2::OfferCodesController < Api::V2::BaseController
before_action(only: [:index, :show]) { doorkeeper_authorize!(*Doorkeeper.configuration.public_scopes.concat([:view_public])) }
before_action(only: [:create, :update, :destroy]) { doorkeeper_authorize! :edit_products }
before_action :check_offer_code_params, only: [:create]
before_action :fetch_product
before_action :fetch_offer_code, only: %i[show update destroy]
def index
offer_codes = @product.product_and_universal_offer_codes
success_with_object(:offer_codes, offer_codes)
end
def create
offer_code = if params[:offer_type] == "percent"
OfferCode.new(code: params[:name],
universal: params[:universal] == "true",
amount_percentage: params[:amount_off].to_i,
max_purchase_count: params[:max_purchase_count])
else
OfferCode.new(code: params[:name],
universal: params[:universal] == "true",
amount_cents: params[:amount_cents].presence || params[:amount_off].presence,
max_purchase_count: params[:max_purchase_count],
currency_type: @product.price_currency_type)
end
offer_code.user = @product.user
offer_code.products << @product unless params[:universal] == "true"
if offer_code.save
success_with_offer_code(offer_code)
else
error_with_creating_object(:offer_code, offer_code)
end
end
def show
success_with_offer_code(@offer_code)
end
def update
if @offer_code.update(permitted_params)
success_with_offer_code(@offer_code)
else
error_with_offer_code(@offer_code)
end
end
def destroy
if @offer_code.update(deleted_at: Time.current)
success_with_offer_code
else
error_with_offer_code
end
end
private
def permitted_params
params.permit(:max_purchase_count)
end
def check_offer_code_params
return if params[:amount_off].present? || params[:amount_cents].present?
render_response(false, message: "You are missing required offer code parameters. Please refer to " \
"https://gumroad.com/api#offer-codes for the correct parameters.")
end
def fetch_offer_code
@offer_code = @product.find_offer_code_by_external_id(params[:id])
error_with_offer_code if @offer_code.nil?
end
def success_with_offer_code(offer_code = nil)
success_with_object(:offer_code, offer_code)
end
def error_with_offer_code(offer_code = nil)
error_with_object(:offer_code, offer_code)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/checkout/upsells_controller.rb | app/controllers/checkout/upsells_controller.rb | # frozen_string_literal: true
class Checkout::UpsellsController < Sellers::BaseController
include Pagy::Backend
PER_PAGE = 20
layout "inertia", only: [:index]
def index
authorize [:checkout, Upsell]
@title = "Upsells"
pagination, upsells = fetch_upsells
upsells_props = Checkout::UpsellsPresenter.new(pundit_user:, pagination:, upsells:).upsells_props
render inertia: "Checkout/Upsells/Index",
props: upsells_props
end
def paged
authorize [:checkout, Upsell]
pagination, upsells = fetch_upsells
render json: { upsells:, pagination: }
end
def cart_item
authorize [:checkout, Upsell]
product = current_seller.products.find_by_external_id!(params[:product_id])
checkout_presenter = CheckoutPresenter.new(logged_in_user: nil, ip: nil)
render json: checkout_presenter.checkout_product(
product,
product.cart_item({
option: product.is_tiered_membership ? product.alive_variants.first.external_id : nil
}),
{}
)
end
def create
authorize [:checkout, Upsell]
@upsell = current_seller.upsells.build
assign_upsell_attributes
set_variant
create_upsell_variants
set_offer_code
if @upsell.save
pagination, upsells = fetch_upsells
render json: { success: true, upsells:, pagination: }
else
render json: { success: false, error: @upsell.errors.first.message }
end
end
def update
@upsell = current_seller.upsells.includes(:product, :offer_code, upsell_variants: [:selected_variant]).find_by_external_id!(params[:id])
authorize [:checkout, @upsell]
assign_upsell_attributes
update_upsell_variants
set_variant
set_offer_code
if @upsell.save
pagination, upsells = fetch_upsells
render json: { success: true, upsells:, pagination: }
else
render json: { success: false, error: @upsell.errors.first.message }
end
end
def destroy
upsell = current_seller.upsells.includes(:offer_code, :upsell_variants).find_by_external_id!(params[:id])
authorize [:checkout, upsell]
upsell.offer_code&.mark_deleted
upsell.upsell_variants.each(&:mark_deleted)
if upsell.mark_deleted
pagination, upsells = fetch_upsells
render json: { success: true, upsells:, pagination: }
else
render json: { success: false, error: upsell.errors.first.message }
end
end
def statistics
upsell = current_seller.upsells.alive.find_by_external_id!(params[:id])
authorize [:checkout, upsell]
statistics = upsell.purchases_that_count_towards_volume
.group(:selected_product_id, :upsell_variant_id)
.select(:selected_product_id, :upsell_variant_id, "SUM(quantity) as total_quantity", "SUM(price_cents) as total_price_cents")
selected_products = {}
upsell_variants = {}
total = 0
revenue_cents = 0
statistics.each do |record|
product_id = ObfuscateIds.encrypt(record.selected_product_id)
selected_products[product_id] = (selected_products[product_id] || 0) + record.total_quantity
upsell_variants[ObfuscateIds.encrypt(record.upsell_variant_id)] = record.total_quantity if record.upsell_variant_id.present?
total += record.total_quantity
revenue_cents += record.total_price_cents
end
render json: {
uses: {
total:,
selected_products:,
upsell_variants:,
},
revenue_cents:,
}
end
private
def upsell_params
params.permit(:name, :text, :description, :cross_sell, :product_id, :variant_id, :universal, :replace_selected_products, :paused, offer_code: [:amount_cents, :amount_percentage], product_ids: [], upsell_variants: [:selected_variant_id, :offered_variant_id])
end
def assign_upsell_attributes
@upsell.assign_attributes(product: current_seller.products.find_by_external_id!(upsell_params[:product_id]), selected_products: current_seller.products.by_external_ids(upsell_params[:product_ids]), **upsell_params.except(:product_id, :variant_id, :product_ids, :offer_code, :upsell_variants))
end
def set_variant
if params[:variant_id].present?
@upsell.variant = BaseVariant.find_by_external_id!(upsell_params[:variant_id])
else
@upsell.variant = nil
end
end
def set_offer_code
if upsell_params[:offer_code].blank?
@upsell.offer_code&.mark_deleted!
@upsell.offer_code = nil
else
offer_code = upsell_params[:offer_code]
offer_code[:amount_cents] ||= nil
offer_code[:amount_percentage] ||= nil
if @upsell.offer_code.present?
@upsell.offer_code.assign_attributes(products: [@upsell.product], **offer_code)
else
@upsell.build_offer_code(user: current_seller, products: [@upsell.product], **offer_code)
end
end
end
def create_upsell_variants
if upsell_params[:upsell_variants].present?
variants = @upsell.product.variants_or_skus
upsell_params[:upsell_variants].each do |upsell_variant|
@upsell.upsell_variants.build(selected_variant: variants.find_by_external_id(upsell_variant[:selected_variant_id]), offered_variant: variants.find_by_external_id(upsell_variant[:offered_variant_id]))
end
end
end
def update_upsell_variants
variants = @upsell.product.variants_or_skus
new_upsell_variants = upsell_params[:upsell_variants] || []
@upsell.upsell_variants.each do |upsell_variant|
new_offered_variant = new_upsell_variants.find { |new_upsell_variant| new_upsell_variant[:selected_variant_id] == upsell_variant.selected_variant.external_id }
if new_offered_variant.present?
upsell_variant.offered_variant = variants.find_by_external_id!(new_offered_variant[:offered_variant_id])
else
upsell_variant.mark_deleted!
end
end
new_upsell_variants.each do |new_upsell_variant|
selected_variant = BaseVariant.find_by_external_id!(new_upsell_variant[:selected_variant_id])
if @upsell.upsell_variants.find_by(selected_variant:).blank?
@upsell.upsell_variants.build(selected_variant:, offered_variant: BaseVariant.find_by_external_id!(new_upsell_variant[:offered_variant_id]))
end
end
end
def paged_params
params.permit(:page, sort: [:key, :direction])
end
def fetch_upsells
upsells = current_seller.upsells
.alive
.not_is_content_upsell
.sorted_by(**paged_params[:sort].to_h.symbolize_keys)
.order(updated_at: :desc)
upsells = upsells.where("name LIKE :query", query: "%#{params[:query]}%") if params[:query].present?
pagination, upsells = pagy(upsells, page: [paged_params[:page].to_i, 1].max, limit: PER_PAGE)
[PagyPresenter.new(pagination).props, upsells]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/checkout/discounts_controller.rb | app/controllers/checkout/discounts_controller.rb | # frozen_string_literal: true
class Checkout::DiscountsController < Sellers::BaseController
include Pagy::Backend
PER_PAGE = 10
before_action :clean_params, only: [:create, :update]
layout "inertia", only: [:index]
def index
authorize [:checkout, OfferCode]
@title = "Discounts"
pagination, offer_codes = fetch_offer_codes
presenter = Checkout::DiscountsPresenter.new(pundit_user:, offer_codes:, pagination:)
render inertia: "Checkout/Discounts/Index",
props: presenter.discounts_props
end
def paged
authorize [:checkout, OfferCode]
pagination, offer_codes = fetch_offer_codes
presenter = Checkout::DiscountsPresenter.new(pundit_user:)
render json: { offer_codes: offer_codes.map { presenter.offer_code_props(_1) }, pagination: }
end
def statistics
offer_code = OfferCode.find_by_external_id!(params[:id])
authorize [:checkout, offer_code]
purchases = offer_code.purchases.counts_towards_offer_code_uses
statistics = purchases.group(:link_id).pluck(:link_id, "SUM(quantity)", "SUM(price_cents)")
products = {}
total = 0
revenue_cents = 0
statistics.each do |(link_id, total_quantity, total_price_cents)|
products[ObfuscateIds.encrypt(link_id)] = total_quantity
total += total_quantity
revenue_cents += total_price_cents
end
render json: { uses: { total:, products: }, revenue_cents: }
end
def create
authorize [:checkout, OfferCode]
parse_date_times
offer_code = current_seller.offer_codes.build(products: current_seller.products.by_external_ids(offer_code_params[:selected_product_ids]), **offer_code_params.except(:selected_product_ids))
if offer_code.save
pagination, offer_codes = fetch_offer_codes
presenter = Checkout::DiscountsPresenter.new(pundit_user:)
render json: { success: true, offer_codes: offer_codes.map { presenter.offer_code_props(_1) }, pagination: }
else
render json: { success: false, error_message: offer_code.errors.full_messages.first }
end
end
def update
offer_code = OfferCode.find_by_external_id!(params[:id])
authorize [:checkout, offer_code]
parse_date_times
if offer_code.update(**offer_code_params.except(:selected_product_ids, :code), products: current_seller.products.by_external_ids(offer_code_params[:selected_product_ids]))
pagination, offer_codes = fetch_offer_codes
presenter = Checkout::DiscountsPresenter.new(pundit_user:)
render json: { success: true, offer_codes: offer_codes.map { presenter.offer_code_props(_1) }, pagination: }
else
render json: { success: false, error_message: offer_code.errors.full_messages.first }
end
end
def destroy
offer_code = OfferCode.find_by_external_id!(params[:id])
authorize [:checkout, offer_code]
if offer_code.mark_deleted(validate: false)
render json: { success: true }
else
render json: { success: false, error_message: offer_code.errors.full_messages.first }
end
end
private
def offer_code_params
params.permit(:name, :code, :universal, :max_purchase_count, :amount_cents, :amount_percentage, :currency_type, :valid_at, :expires_at, :minimum_quantity, :duration_in_billing_cycles, :minimum_amount_cents, selected_product_ids: [])
end
def paged_params
params.permit(:page, sort: [:key, :direction])
end
def clean_params
params[:currency_type] = nil if params[:currency_type].blank?
if offer_code_params[:amount_percentage].present?
params[:amount_cents] = nil
params[:currency_type] = nil
else
params[:amount_percentage] = nil
end
end
def parse_date_times
offer_code_params[:valid_at] = Time.zone.parse(offer_code_params[:valid_at]) if offer_code_params[:valid_at].present?
offer_code_params[:expires_at] = Time.zone.parse(offer_code_params[:expires_at]) if offer_code_params[:expires_at].present?
end
def fetch_offer_codes
# Map user-facing query params to internal params
params[:sort] = { key: params[:column], direction: params[:sort] } if params[:column].present? && params[:sort].present?
offer_codes = current_seller.offer_codes
.alive
.where.not(code: nil)
.includes(:products)
.sorted_by(**paged_params[:sort].to_h.symbolize_keys).order(updated_at: :desc)
offer_codes = offer_codes.where("name LIKE :query OR code LIKE :query", query: "%#{params[:query]}%") if params[:query].present?
offer_codes_count = offer_codes.count.is_a?(Hash) ? offer_codes.count.length : offer_codes.count
# Map invalid page numbers to the closest valid page number
total_pages = (offer_codes_count / PER_PAGE.to_f).ceil
page_num = paged_params[:page].to_i
if page_num <= 0
page_num = 1
elsif page_num > total_pages && total_pages != 0
page_num = total_pages
end
pagination, offer_codes = pagy(offer_codes, page: page_num, limit: PER_PAGE)
[PagyPresenter.new(pagination).props, offer_codes]
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/checkout/form_controller.rb | app/controllers/checkout/form_controller.rb | # frozen_string_literal: true
class Checkout::FormController < Sellers::BaseController
layout "inertia", only: [:show]
def show
authorize [:checkout, :form]
@title = "Checkout form"
form_props = Checkout::FormPresenter.new(pundit_user:).form_props
render inertia: "Checkout/Form/Show",
props: form_props
end
def update
authorize [:checkout, :form]
begin
ActiveRecord::Base.transaction do
current_seller.update!(permitted_params[:user]) if permitted_params[:user]
if permitted_params[:custom_fields]
all_fields = current_seller.custom_fields.to_a
permitted_params[:custom_fields].each do |field|
existing = all_fields.extract! { _1.external_id == field[:id] }[0] || current_seller.custom_fields.build
existing.update!(field.except(:id, :products))
existing.products = field[:global] ? [] : current_seller.products.by_external_ids(field[:products])
end
all_fields.each(&:destroy)
current_seller.custom_fields.reload
end
end
render json: Checkout::FormPresenter.new(pundit_user:).form_props
rescue ActiveRecord::RecordInvalid => e
render json: { error_message: e.record.errors.full_messages.to_sentence }, status: :unprocessable_entity
end
end
private
def permitted_params
params.permit(policy([:checkout, :form]).permitted_attributes)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/checkout/upsells/pauses_controller.rb | app/controllers/checkout/upsells/pauses_controller.rb | # frozen_string_literal: true
class Checkout::Upsells::PausesController < Sellers::BaseController
before_action :set_upsell!
after_action :verify_authorized
def create
authorize [:checkout, @upsell], :pause?
@upsell.update!(paused: true)
head :no_content
end
def destroy
authorize [:checkout, @upsell], :unpause?
@upsell.update!(paused: false)
head :no_content
end
private
def set_upsell!
@upsell = current_seller.upsells.alive.find_by_external_id!(params[:upsell_id])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/checkout/upsells/products_controller.rb | app/controllers/checkout/upsells/products_controller.rb | # frozen_string_literal: true
class Checkout::Upsells::ProductsController < ApplicationController
include CustomDomainConfig
def index
seller = user_by_domain(request.host) || current_seller
render json: seller.products.eligible_for_content_upsells.map { |product| Checkout::Upsells::ProductPresenter.new(product).product_props }
end
def show
product = Link.eligible_for_content_upsells
.find_by_external_id!(params[:id])
render json: Checkout::Upsells::ProductPresenter.new(product).product_props
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/oauth/tokens_controller.rb | app/controllers/oauth/tokens_controller.rb | # frozen_string_literal: true
class Oauth::TokensController < Doorkeeper::TokensController
include LogrageHelper
private
def strategy
# default to authorization code
params[:grant_type] = "authorization_code" if params[:grant_type].blank?
super
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/oauth/authorizations_controller.rb | app/controllers/oauth/authorizations_controller.rb | # frozen_string_literal: true
class Oauth::AuthorizationsController < Doorkeeper::AuthorizationsController
before_action :hide_layouts
before_action :default_to_authorization_code
before_action :hide_from_search_results
private
def hide_layouts
@hide_layouts = true
end
def hide_from_search_results
headers["X-Robots-Tag"] = "noindex"
end
def default_to_authorization_code
params[:response_type] = "code" if params[:response_type].blank?
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/oauth/access_tokens_controller.rb | app/controllers/oauth/access_tokens_controller.rb | # frozen_string_literal: true
class Oauth::AccessTokensController < Sellers::BaseController
before_action :set_application
def create
authorize [:settings, :authorized_applications, @application]
access_token = @application.get_or_generate_access_token
render json: { success: true, token: access_token.token }
end
private
def set_application
@application = current_seller.oauth_applications.alive.find_by_external_id(params[:application_id])
return if @application.present?
render json: { success: false, message: "Application not found or you don't have the permissions to modify it." }, status: :not_found
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/oauth/applications_controller.rb | app/controllers/oauth/applications_controller.rb | # frozen_string_literal: true
class Oauth::ApplicationsController < Doorkeeper::ApplicationsController
protect_from_forgery
include CsrfTokenInjector
include Impersonate
before_action :authenticate_user!
before_action :set_application_params, only: %i[create update]
before_action :set_application, only: %i[edit update destroy]
after_action :verify_authorized, except: %i[index new show]
layout "inertia"
def index
redirect_to settings_advanced_path
end
def new
redirect_to settings_advanced_path
end
def create
@application = OauthApplication.new
authorize([:settings, :authorized_applications, @application])
@application.name = @application_params[:name]
@application.redirect_uri = @application_params[:redirect_uri]
@application.owner = current_seller
@application.owner_type = "User"
if params[:signed_blob_id].present?
@application.file.attach(params[:signed_blob_id])
end
if @application.save
redirect_to edit_oauth_application_path(@application.external_id), notice: "Application created."
else
redirect_to settings_advanced_path, alert: @application.errors.full_messages.to_sentence
end
end
def show
redirect_to edit_oauth_application_path(params[:id])
end
def edit
@title = "Update application"
authorize([:settings, :authorized_applications, @application])
settings_presenter = SettingsPresenter.new(pundit_user:)
render inertia: "Oauth/Applications/Edit",
props: settings_presenter.application_props(@application)
end
def update
authorize([:settings, :authorized_applications, @application])
@application.name = @application_params[:name] if @application_params[:name].present?
@application.redirect_uri = @application_params[:redirect_uri] if @application_params[:redirect_uri].present?
if params[:signed_blob_id].present?
@application.file.attach(params[:signed_blob_id])
end
if @application.save
redirect_to edit_oauth_application_path(@application.external_id), notice: "Application updated."
else
redirect_to edit_oauth_application_path(@application.external_id),
alert: @application.errors.full_messages.to_sentence
end
end
def destroy
authorize([:settings, :authorized_applications, @application])
@application.mark_deleted!
redirect_to settings_advanced_path, notice: "Application deleted."
end
private
def set_application_params
@application_params = if params[:oauth_application].respond_to?(:slice)
params[:oauth_application].slice(:name, :redirect_uri, :affiliate_percent)
else
{}
end
end
def set_application
@application = current_seller.oauth_applications.alive.find_by_external_id(params[:id])
return if @application.present?
respond_to do |format|
format.json do
render json: { success: false,
message: "Application not found or you don't have the permissions to modify it.",
redirect_location: oauth_applications_url }
end
format.html do
flash[:alert] = "Application not found or you don't have the permissions to modify it."
redirect_to oauth_applications_url
end
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/oauth/authorized_applications_controller.rb | app/controllers/oauth/authorized_applications_controller.rb | # frozen_string_literal: true
class Oauth::AuthorizedApplicationsController < Doorkeeper::AuthorizedApplicationsController
def index
redirect_to settings_authorized_applications_path
end
def destroy
application = OauthApplication.authorized_for(current_resource_owner).find_by_external_id(params[:id])
if application.present?
application.revoke_access_for(current_resource_owner)
redirect_to settings_authorized_applications_path, notice: "Authorized application revoked"
else
redirect_to settings_authorized_applications_path, alert: "Authorized application could not be revoked"
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/oauth/notion/authorizations_controller.rb | app/controllers/oauth/notion/authorizations_controller.rb | # frozen_string_literal: true
class Oauth::Notion::AuthorizationsController < Oauth::AuthorizationsController
before_action :retrieve_notion_bot_token, only: [:new]
private
def retrieve_notion_bot_token
if params[:code].present?
response = NotionApi.new.get_bot_token(code: params[:code], user: current_resource_owner)
Rails.logger.info "Retrieved Notion Bot Token: #{response.body.inspect}" if Rails.env.development?
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/products/other_refund_policies_controller.rb | app/controllers/products/other_refund_policies_controller.rb | # frozen_string_literal: true
class Products::OtherRefundPoliciesController < Sellers::BaseController
include FetchProductByUniquePermalink
def index
fetch_product_by_unique_permalink
authorize @product, :edit?
product_refund_policies = @product.user
.product_refund_policies
.for_visible_and_not_archived_products
.where.not(product_id: @product.id)
.order(updated_at: :desc)
.select("refund_policies.*", "links.name")
render json: product_refund_policies
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/products/remaining_call_availabilities_controller.rb | app/controllers/products/remaining_call_availabilities_controller.rb | # frozen_string_literal: true
class Products::RemainingCallAvailabilitiesController < ApplicationController
include FetchProductByUniquePermalink
before_action :fetch_product_by_unique_permalink
def index
if @product.native_type == Link::NATIVE_TYPE_CALL
render json: { call_availabilities: @product.remaining_call_availabilities }
else
head :not_found
end
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/products/archived_controller.rb | app/controllers/products/archived_controller.rb | # frozen_string_literal: true
class Products::ArchivedController < Sellers::BaseController
include ProductsHelper
PER_PAGE = 50
before_action :fetch_product_and_enforce_ownership, only: %i[create destroy]
layout "inertia", only: [:index]
def index
authorize [:products, :archived, Link]
memberships_pagination, memberships = paginated_memberships(page: 1)
products_pagination, products = paginated_products(page: 1)
return redirect_to products_url if memberships.none? && products.none?
props = DashboardProductsPagePresenter.new(
pundit_user:,
memberships:,
memberships_pagination:,
products:,
products_pagination:
).page_props
@title = "Archived products"
render inertia: "Products/Archived/Index", props:
end
def products_paged
authorize [:products, :archived, Link], :index?
products_pagination, products = paginated_products(page: params[:page].to_i, query: params[:query])
react_products_page_props = DashboardProductsPagePresenter.new(
pundit_user:,
products:,
products_pagination:,
memberships: nil,
memberships_pagination: nil
).products_table_props
render json: {
pagination: react_products_page_props[:products_pagination],
entries: react_products_page_props[:products]
}
end
def memberships_paged
authorize [:products, :archived, Link], :index?
memberships_pagination, memberships = paginated_memberships(page: paged_params[:page].to_i, query: params[:query])
react_products_page_props = DashboardProductsPagePresenter.new(
pundit_user:,
products: nil,
products_pagination: nil,
memberships:,
memberships_pagination:
).memberships_table_props
render json: {
pagination: react_products_page_props[:memberships_pagination],
entries: react_products_page_props[:memberships]
}
end
def create
authorize [:products, :archived, @product]
@product.update!(
archived: true,
purchase_disabled_at: @product.purchase_disabled_at || Time.current
)
render json: { success: true }
end
def destroy
authorize [:products, :archived, @product]
@product.update!(archived: false)
render json: { success: true, archived_products_count: current_seller.archived_products_count }
end
private
def paged_params
params.permit(:page, sort: [:key, :direction])
end
def paginated_memberships(page:, query: nil)
memberships = current_seller.products.membership.visible.archived
memberships = memberships.where("name like ?", "%#{query}%") if query.present?
sort_and_paginate_products(**paged_params[:sort].to_h.symbolize_keys, page:, collection: memberships, per_page: PER_PAGE, user_id: current_seller.id)
end
def paginated_products(page:, query: nil)
products = current_seller.products.non_membership.visible.archived
products = products.where("name like ?", "%#{query}%") if query.present?
sort_and_paginate_products(**paged_params[:sort].to_h.symbolize_keys, page:, collection: products, per_page: PER_PAGE, user_id: current_seller.id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/products/mobile_tracking_controller.rb | app/controllers/products/mobile_tracking_controller.rb | # frozen_string_literal: true
class Products::MobileTrackingController < ApplicationController
before_action :hide_layouts
def show
product = Link.fetch(params[:link_id])
@tracking_props = MobileTrackingPresenter.new(seller: product.user).product_props(product:)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/products/collabs_controller.rb | app/controllers/products/collabs_controller.rb | # frozen_string_literal: true
class Products::CollabsController < Sellers::BaseController
before_action :authorize
layout "inertia", only: [:index]
def index
@title = "Products"
props = CollabProductsPagePresenter.new(**presenter_params).initial_page_props
respond_to do |format|
format.html { render inertia: "Products/Collabs/Index", props: }
format.json { render json: props }
end
end
def memberships_paged
props = CollabProductsPagePresenter.new(**presenter_params).memberships_table_props
render json: {
pagination: props[:memberships_pagination],
entries: props[:memberships],
}
end
def products_paged
props = CollabProductsPagePresenter.new(**presenter_params).products_table_props
render json: {
pagination: props[:products_pagination],
entries: props[:products],
}
end
private
def authorize
super([:products, :collabs])
end
def presenter_params
permitted_params = params.permit(:page, :query, sort: [:key, :direction])
{
pundit_user:,
page: permitted_params[:page].to_i,
sort_params: permitted_params[:sort],
query: permitted_params[:query],
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/products/variants_controller.rb | app/controllers/products/variants_controller.rb | # frozen_string_literal: true
class Products::VariantsController < Sellers::BaseController
def index
fetch_product_and_enforce_ownership
authorize [:products, :variants, @product]
render json: @product.options
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/products/affiliated_controller.rb | app/controllers/products/affiliated_controller.rb | # frozen_string_literal: true
class Products::AffiliatedController < Sellers::BaseController
before_action :authorize
layout "inertia", only: [:index]
def index
@title = "Products"
props = AffiliatedProductsPresenter.new(current_seller,
query: affiliated_products_params[:query],
page: affiliated_products_params[:page],
sort: affiliated_products_params[:sort])
.affiliated_products_page_props
respond_to do |format|
format.html { render inertia: "Products/Affiliated/Index", props: }
format.json { render json: props }
end
end
private
def authorize
super([:products, :affiliated])
end
def affiliated_products_params
params.permit(:query, :page, sort: [:key, :direction])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/internal/base_controller.rb | app/controllers/internal/base_controller.rb | # frozen_string_literal: true
class Internal::BaseController < ApplicationController
def authorize_request
return render json: { success: false }, status: :unauthorized if request.authorization.nil?
decoded_credentials = ::Base64.decode64(request.authorization.split(" ", 2).last || "").split(":")
username = decoded_credentials[0]
password = decoded_credentials[1]
render json: { success: false }, status: :unauthorized if username != SPEC_API_USERNAME || password != SPEC_API_PASSWORD
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/sellers/switch_controller.rb | app/controllers/sellers/switch_controller.rb | # frozen_string_literal: true
class Sellers::SwitchController < Sellers::BaseController
before_action :skip_authorization
def create
team_membership = find_team_membership!(external_team_membership_id)
switch_seller_account(team_membership)
head :no_content
rescue ActiveRecord::RecordNotFound
head :no_content
end
private
def find_team_membership!(external_team_membership_id)
logged_in_user.user_memberships
.not_deleted
.find_by_external_id!(external_team_membership_id)
end
def external_team_membership_id
params.require(:team_membership_id)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/sellers/base_controller.rb | app/controllers/sellers/base_controller.rb | # frozen_string_literal: true
class Sellers::BaseController < ApplicationController
before_action :authenticate_user!
after_action :verify_authorized
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/users/oauth_controller.rb | app/controllers/users/oauth_controller.rb | # frozen_string_literal: true
class Users::OauthController < UsersController
def async_facebook_create
user = User.verify_facebook_login(params[:accessToken])
if user.present?
sign_in user
render json: { success: true }
else
render json: { success: false }
end
end
def async_facebook_store_token
access_token = params[:accessToken]
begin
oauth = Koala::Facebook::OAuth.new(FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
access_token = oauth.exchange_access_token(access_token)
profile = Koala::Facebook::API.new(access_token).get_object("me")
logged_in_user.facebook_access_token = access_token
logged_in_user.facebook_uid = profile["id"]
render json: { success: logged_in_user.save }
rescue Koala::Facebook::APIError, *INTERNET_EXCEPTIONS => e
logger.error "Error storing long-lived Facebook access token: #{e.message}"
render json: { success: false }
end
end
def check_twitter_link
render json: { success: logged_in_user.twitter_user_id.present? }
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/global_affiliates/product_eligibility_controller.rb | app/controllers/global_affiliates/product_eligibility_controller.rb | # frozen_string_literal: true
class GlobalAffiliates::ProductEligibilityController < Sellers::BaseController
class InvalidUrl < StandardError; end
GUMROAD_DOMAINS = [ROOT_DOMAIN, SHORT_DOMAIN, DOMAIN].map { |domain| Addressable::URI.parse("#{PROTOCOL}://#{domain}").domain } # Strip port (in test and development environment) and subdomains
EXPECTED_PRODUCT_PARAMS = %w(name formatted_price recommendable short_url)
def show
authorize [:products, :affiliated], :index?
product_data = fetch_and_parse_product_data
render json: { success: true, product: product_data }
rescue InvalidUrl
render json: { success: false, error: "Please provide a valid Gumroad product URL" }
end
private
def fetch_and_parse_product_data
uri = Addressable::URI.parse(params[:url])
raise InvalidUrl unless GUMROAD_DOMAINS.include?(uri&.domain)
uri.path = uri.path + ".json"
response = HTTParty.get(uri.to_s)
raise InvalidUrl unless response.ok?
data = response.to_hash.slice(*EXPECTED_PRODUCT_PARAMS)
raise InvalidUrl unless data.keys == EXPECTED_PRODUCT_PARAMS
data
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/gumroad_blog/posts_controller.rb | app/controllers/gumroad_blog/posts_controller.rb | # frozen_string_literal: true
class GumroadBlog::PostsController < GumroadBlog::BaseController
layout "gumroad_blog"
before_action :hide_layouts
before_action :set_blog_owner!
before_action :set_post, only: [:show]
after_action :verify_authorized
def index
authorize [:gumroad_blog, :posts]
posts = @blog_owner.installments
.visible_on_profile
.order(published_at: :desc)
@props = {
posts: posts.map do |post|
{
url: gumroad_blog_post_path(post.slug),
subject: post.subject,
published_at: post.published_at,
featured_image_url: post.featured_image_url,
message_snippet: post.message_snippet,
tags: post.tags,
}
end,
}
end
def show
authorize @post, policy_class: GumroadBlog::PostsPolicy
@props = PostPresenter.new(pundit_user: pundit_user, post: @post, purchase_id_param: nil).post_component_props
end
private
def set_post
@post = @blog_owner.installments.find_by!(slug: params[:slug])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/gumroad_blog/base_controller.rb | app/controllers/gumroad_blog/base_controller.rb | # frozen_string_literal: true
class GumroadBlog::BaseController < ApplicationController
private
def set_blog_owner!
owner_username = GlobalConfig.get("BLOG_OWNER_USERNAME", "gumroad")
@blog_owner = User.find_by!(username: owner_username)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/product_review_videos/streams_controller.rb | app/controllers/product_review_videos/streams_controller.rb | # frozen_string_literal: true
class ProductReviewVideos::StreamsController < ApplicationController
before_action :set_product_review_video
def show
respond_to do |format|
format.smil { render plain: @product_review_video.video_file.smil_xml }
end
end
private
def set_product_review_video
@product_review_video = ProductReviewVideo.alive.find_by_external_id!(params[:product_review_video_id])
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/product_review_videos/streaming_urls_controller.rb | app/controllers/product_review_videos/streaming_urls_controller.rb | # frozen_string_literal: true
class ProductReviewVideos::StreamingUrlsController < ApplicationController
before_action :set_product_review_video
after_action :verify_authorized
def index
return head :unauthorized unless authorized?
render json: {
streaming_urls: [
product_review_video_stream_path(
@product_review_video.external_id,
format: :smil
),
@product_review_video.video_file.signed_download_url
]
}
end
private
def set_product_review_video
@product_review_video = ProductReviewVideo.alive
.find_by_external_id!(params[:product_review_video_id])
end
def authorized?
if authorize_anonymous_user_access?
skip_authorization
true
else
authorize @product_review_video, :stream?
end
end
def authorize_anonymous_user_access?
@product_review_video.approved? || authorized_by_purchase_email_digest?
end
def authorized_by_purchase_email_digest?
ActiveSupport::SecurityUtils.secure_compare(
@product_review_video.product_review.purchase.email_digest,
params[:purchase_email_digest].to_s
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/product_review_videos/upload_contexts_controller.rb | app/controllers/product_review_videos/upload_contexts_controller.rb | # frozen_string_literal: true
class ProductReviewVideos::UploadContextsController < ApplicationController
before_action :authenticate_user!
def show
render json: {
aws_access_key_id: AWS_ACCESS_KEY,
s3_url: "#{AWS_S3_ENDPOINT}/#{S3_BUCKET}",
user_id: logged_in_user.external_id,
}
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/discover/search_autocomplete_controller.rb | app/controllers/discover/search_autocomplete_controller.rb | # frozen_string_literal: true
class Discover::SearchAutocompleteController < ApplicationController
include CreateDiscoverSearch
def search
create_discover_search!(query: params[:query], autocomplete: true) if params[:query].present?
render json: Discover::AutocompletePresenter.new(
query: params[:query],
user: logged_in_user,
browser_guid: cookies[:_gumroad_guid]
).props
end
def delete_search_suggestion
DiscoverSearchSuggestion
.by_user_or_browser(user: logged_in_user, browser_guid: cookies[:_gumroad_guid])
.where(discover_searches: { query: params[:query] })
.each(&:mark_deleted!)
head :no_content
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
antiwork/gumroad | https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/app/controllers/discover/recommended_wishlists_controller.rb | app/controllers/discover/recommended_wishlists_controller.rb | # frozen_string_literal: true
class Discover::RecommendedWishlistsController < ApplicationController
def index
wishlists = RecommendedWishlistsService.fetch(
limit: 4,
current_seller:,
curated_product_ids: (params[:curated_product_ids] || []).map { ObfuscateIds.decrypt(_1) },
taxonomy_id: params[:taxonomy].present? ? Taxonomy.find_by_path(params[:taxonomy].split("/")).id : nil
)
render json: WishlistPresenter.cards_props(
wishlists:,
pundit_user:,
layout: Product::Layout::DISCOVER,
recommended_by: RecommendationType::GUMROAD_DISCOVER_WISHLIST_RECOMMENDATION,
)
end
end
| ruby | MIT | 638f6c3a40b23b907c09f6881d4df18339da069c | 2026-01-04T15:39:11.815677Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.