Marketplace Service
요약
메서드
이벤트
PromptBulkPurchaseFinished(player: Instance,status: Enum.MarketplaceBulkPurchasePromptStatus,results: Dictionary):RBXScriptSignal |
PromptBundlePurchaseFinished(player: Instance,bundleId: number,wasPurchased: boolean):RBXScriptSignal |
PromptGamePassPurchaseFinished(player: Instance,gamePassId: number,wasPurchased: boolean):RBXScriptSignal |
PromptProductPurchaseFinished(userId: number,productId: number,isPurchased: boolean):RBXScriptSignal |
PromptPurchaseFinished(player: Instance,assetId: number,isPurchased: boolean):RBXScriptSignal |
PromptRobloxSubscriptionPurchaseFinished(user: Player,didTryPurchasing: boolean):RBXScriptSignal |
PromptSubscriptionPurchaseFinished(user: Player,subscriptionId: string,didTryPurchasing: boolean):RBXScriptSignal |
콜백
ProcessReceipt(receiptInfo: Dictionary):Enum.ProductPurchaseDecision |
상속된 멤버
API 참조
메서드
Bind Receipt Handler
Marketplace Service: Bind Receipt Handler(
매개 변수
코드 샘플
MarketplaceService:BindReceiptHandler
-- 주의: 핸들러가 지속적인 혜택(통화, 아이템)을 부여하는 경우,
-- DataStoreService:UpdateAsync()를 TransferRequestId에 사용하여
-- 동일한 영수증이 여러 서버에 전달될 때 이중 부여를 방지하세요.
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
-- 송신자 영수증 처리 (Robux를 보낸 플레이어)
MarketplaceService:BindReceiptHandler(
Enum.ReceiptType.RobuxTransferSender,
function(receiptInfo)
local player = Players:GetPlayerByUserId(receiptInfo.PlayerId)
if not player then
-- 플레이어가 이 서버에 없습니다; 영수증이
-- 현재 있는 서버로 다시 전달되도록 지연합니다.
return Enum.ReceiptDecision.NotProcessedYet
end
print(
`{player.Name}가 {receiptInfo.CurrencySpent} Robux를 보냈습니다.`
.. ` (TransferRequestId: {receiptInfo.TransferRequestId})`
)
-- 여기서 송신자 측 확인 또는 UI 업데이트를 부여합니다.
return Enum.ReceiptDecision.Processed
end
)
-- 수신자 영수증 처리 (Robux를 받은 플레이어)
MarketplaceService:BindReceiptHandler(
Enum.ReceiptType.RobuxTransferReceiver,
function(receiptInfo)
local player = Players:GetPlayerByUserId(receiptInfo.PlayerId)
if not player then
return Enum.ReceiptDecision.NotProcessedYet
end
print(
`{player.Name}가 {receiptInfo.CurrencySpent} Robux를 받았습니다.`
.. ` (TransferRequestId: {receiptInfo.TransferRequestId})`
)
-- 여기서 수신자 측 혜택 또는 UI 업데이트를 부여합니다.
return Enum.ReceiptDecision.Processed
end
)MarketplaceService:BindReceiptHandler
local MarketplaceService = game:GetService("MarketplaceService")
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
-- 100 코인을 부여하는 개발자 제품 ID로 교체하세요
local COINS_PRODUCT_ID = 123456789
local COINS_PER_PURCHASE = 100
local purchaseHistoryStore = DataStoreService:GetDataStore("PurchaseHistory")
-- 필터 배열을 전달하면 이 핸들러는 나열된 제품 ID에만 바인딩됩니다.
-- 필터를 생략하면 필터링된 핸들러에 의해 청구되지 않은 모든
-- 개발자 제품 영수증에 대해 작동하는 catch-all 핸들러가 등록됩니다.
MarketplaceService:BindReceiptHandler(
Enum.ReceiptType.DeveloperProduct,
function(receiptInfo)
local player = Players:GetPlayerByUserId(receiptInfo.PlayerId)
if not player then
-- 구매자가 이 서버에 없습니다; 영수증을 지연시켜
-- 나중에 다시 전달되거나 다음에 서버에 참여할 때 전달됩니다
return Enum.ReceiptDecision.NotProcessedYet
end
-- 동일한 영수증이 여러 번 전달되더라도 제품을 정확히 한 번만 부여합니다.
-- PurchaseId를 기준으로 하여. 콜백은 이점이 영구적으로 부여될 때만
-- true를 기록하므로 UpdateAsync는 이 영수증이 완료될 때 정확히 true로 해결됩니다.
local success, granted = pcall(function()
return purchaseHistoryStore:UpdateAsync(receiptInfo.PurchaseId, function(alreadyGranted)
if alreadyGranted then
-- 이전 전달이 이미 이 구매를 부여했습니다; 다시
-- 부여하지 말고 영수증을 해결된 상태로 유지합니다
return true
end
local leaderstats = player:FindFirstChild("leaderstats")
local coins = leaderstats and leaderstats:FindFirstChild("Coins")
if not coins then
-- 플레이어의 통계가 아직 준비되지 않았습니다. nil을 반환하여
-- 기록이 부여되지 않도록 취소하고
-- 영수증이 나중에 다시 전달되도록 합니다
return nil
end
coins.Value += COINS_PER_PURCHASE
return true
end)
end)
if not success or granted ~= true then
-- 데이터 저장소 오류가 발생했거나 이점이 부여되지 않았습니다; 영수증을
-- 해결되지 않은 상태로 두어 나중에 다시 전달되도록 합니다
return Enum.ReceiptDecision.NotProcessedYet
end
return Enum.ReceiptDecision.Processed
end,
{ COINS_PRODUCT_ID }
)Get Developer Products Async
반환
코드 샘플
MarketplaceService:GetDeveloperProductsAsync
local MarketplaceService = game:GetService("MarketplaceService")
local developerProducts = MarketplaceService:GetDeveloperProductsAsync():GetCurrentPage()
for _, developerProduct in pairs(developerProducts) do
for field, value in pairs(developerProduct) do
print(field .. ": " .. value)
end
print(" ")
endGet Product Info
Get Product Info Async
매개 변수
| 기본값: Asset |
코드 샘플
상품 정보 가져오기
local MarketplaceService = game:GetService("MarketplaceService")
local ASSET_ID = 125378389
local asset = MarketplaceService:GetProductInfoAsync(ASSET_ID)
print(asset.Name .. " :: " .. asset.Description)가격 할인 표시
local MarketplaceService = game:GetService("MarketplaceService")
local PASS_ID = 12345678
local DiscountTypeDisplay = {
RobloxPlusSubscription = "로블록스 플러스 할인",
}
local productInfo = MarketplaceService:GetProductInfoAsync(PASS_ID, Enum.InfoType.GamePass)
print(string.format("원래 가격: %d", productInfo.UserBasePriceInRobux))
for _, discount in ipairs(productInfo.PriceDiscountDetails) do
local displayName = DiscountTypeDisplay[discount.Type] or "기타 할인"
print(string.format("%s (%d%%): -%d", displayName, discount.Percent, discount.AmountInRobux))
end
print(string.format("당신이 지불하는 금액: %d", productInfo.PriceInRobux))사용 가능한 시간 옵션 표시
local MarketplaceService = game:GetService("MarketplaceService")
local info = MarketplaceService:GetProductInfoAsync(105589844216517, Enum.InfoType.Asset)
if info.TimedOptions then
for _, option in info.TimedOptions do
local days = option.Duration / 86400
print(string.format("%d일 - %d Robux", days, option.Price))
end
end투명 배칭을 통한 병렬 GetProductInfoAsync
local MarketplaceService = game:GetService("MarketplaceService")
local productIds = {123456, 987654, 555777}
local results = {}
local remaining = #productIds
local function fetch(productId)
local success, info = pcall(function()
return MarketplaceService:GetProductInfoAsync(productId, Enum.InfoType.Product)
end)
if success then
results[productId] = info
else
warn("제품 정보를 가져오는 데 실패했습니다:", productId, info)
end
remaining -= 1
end
-- 모든 호출을 동시에 생성하면 엔진이 이를 자동으로
-- 더 적은 HTTP 요청으로 배치할 수 있습니다.
for _, productId in productIds do
task.spawn(fetch, productId)
end
-- 모든 요청이 완료될 때까지 기다립니다.
while remaining > 0 do
task.wait()
end
-- 이제 모든 결과를 사용할 수 있습니다.
for productId, info in results do
print(info.Name, "-", info.PriceInRobux, "Robux")
endGet Roblox Subscription Details Async
매개 변수
코드 샘플
로블록스 구독 세부정보 확인
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local success, details = pcall(function()
return MarketplaceService:GetRobloxSubscriptionDetailsAsync(player)
end)
if success and details.IsSubscribed then
-- 1. 충성도 확인 (예: 60일 이상 구독)
local threeMonths = 60 * 24 * 60 * 60
if details.StartTime and (os.time() - details.StartTime.UnixTimestamp) > threeMonths then
print("'3개월 구독 베테랑' 스킨을 수여합니다!")
end
-- 2. 기여도 확인
if details.IsOriginExperience then
print("기여도가 확인되었습니다: 사용자가 이 경험을 통해 구독했습니다.")
else
print("사용자가 다른 곳(웹사이트 또는 다른 경험)에서 구독했습니다.")
end
end
end)Get Subscription Product Info Async
매개 변수
Get Users Price Levels Async
매개 변수
반환
{PriceLevelInfo}
코드 샘플
사용자 목록의 가격 수준 가져오기
-- MarketplaceService 가져오기
local MarketplaceService = game:GetService("MarketplaceService")
-- 사용자 목록에 대한 가격 레벨을 가져오는 함수 정의
local function getPriceLevels(userIds)
local success, result = pcall(function()
return MarketplaceService:GetUsersPriceLevelsAsync(userIds)
end)
if success then
-- 각 PriceLevelInfo를 UserId -> PriceLevel 조회 테이블로 매핑
local lookup = {}
for _, info in ipairs(result) do
lookup[info.UserId] = info.PriceLevel
end
return lookup
else
warn("가격 레벨을 가져오는 중 오류 발생:", result)
return nil
end
end
-- 자리 표시자 ID를 사용한 예시
local user1Id = 123456789
local user2Id = 987654321
-- 함수를 호출하고 결과를 저장
local priceLevels = getPriceLevels({user1Id, user2Id})
-- 성공적인 경우 각 사용자의 레벨 출력
if priceLevels then
print("사용자 1의 가격 레벨:", priceLevels[user1Id])
print("사용자 2의 가격 레벨:", priceLevels[user2Id])
else
print("가격 레벨을 가져오는 데 실패하였습니다.")
endGet User Subscription Details Async
Get User Subscription Payment History Async
반환
코드 샘플
MarketplaceService:GetUserSubscriptionPaymentHistoryAsync
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
local SUBSCRIPTION_ID = "EXP-0"
local function checkSubscriptionHistory(player: Player)
local subscriptionHistory = {}
local success, err = pcall(function()
subscriptionHistory = MarketplaceService:GetUserSubscriptionPaymentHistoryAsync(player, SUBSCRIPTION_ID)
end)
if not success then
warn(`구독 내역 확인 중 오류 발생: {err}`)
return
end
if next(subscriptionHistory) then
-- 사용자는 지난 12개월 동안 일부 구독 내역이 있습니다.
-- 구독 내역의 각 결제 항목의 세부 정보를 출력합니다.
print(`플레이어 {player.Name}는 이전에 {SUBSCRIPTION_ID}에 구독했습니다:`)
for entryNum, paymentEntry in subscriptionHistory do
local paymentStatus = tostring(paymentEntry.PaymentStatus)
local cycleStartTime = paymentEntry.CycleStartTime:FormatLocalTime("LLL", "en-us")
local cycleEndTime = paymentEntry.CycleEndTime:FormatLocalTime("LLL", "en-us")
print(`{entryNum}: {paymentStatus} ({cycleStartTime} - {cycleEndTime})`)
end
else
print(`플레이어 {player.Name}는 이전에 {SUBSCRIPTION_ID}에 구독한 적이 없습니다.`)
end
end
-- 게임에 이미 있는 모든 플레이어에 대해 checkSubscriptionHistory 호출
for _, player in ipairs(Players:GetPlayers()) do
checkSubscriptionHistory(player)
end
-- 모든 미래 플레이어에 대해 checkSubscriptionHistory 호출
Players.PlayerAdded:Connect(checkSubscriptionHistory)Get User Subscription Status Async
코드 샘플
사용자 구독 상태 확인
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
local subscriptionID = "EXP-00000"
local function checkSubStatus(player)
local subStatus = {}
local success, message = pcall(function()
-- IsRenewing 및 IsSubscribed를 반화합니다.
subStatus = MarketplaceService:GetUserSubscriptionStatusAsync(player, subscriptionID)
end)
if not success then
warn("플레이어의 구독 여부 확인 중 오류 발생: " .. tostring(message))
return
end
if subStatus["IsSubscribed"] then
print(player.Name .. "는 " .. subscriptionID .. "로 구독 중입니다.")
-- 구독과 관련된 권한을 플레이어에게 부여합니다.
end
end
Players.PlayerAdded:Connect(checkSubStatus)Open Shop
매개 변수
반환
()
코드 샘플
게임 내 상점 열기
설명: 이 코드 샘플은 로컬 플레이어를 위한 게임 내 상점을 여는 방법을 보여줍니다.
상점은 게임의 패스와 개발자 제품의 개인화된 목록을 표시합니다.
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
MarketplaceService:OpenShop(player)Player Owns Asset
Player Owns Asset Async
반환
코드 샘플
아이템 소유 확인
local Players = game:GetService("Players")
local MarketplaceService = game:GetService("MarketplaceService")
-- 확인할 아이템: https://www.roblox.com/catalog/30331986/Midnight-Shades
local ASSET_ID = 30331986
local ASSET_NAME = "Midnight Shades"
local function onPlayerAdded(player)
local success, doesPlayerOwnAsset =
pcall(MarketplaceService.PlayerOwnsAssetAsync, MarketplaceService, player, ASSET_ID)
if not success then
local errorMessage = doesPlayerOwnAsset
warn(`{player.Name}가 {ASSET_NAME}를 소유하고 있는지 확인하는 중 오류 발생: {errorMessage}`)
return
end
if doesPlayerOwnAsset then
print(`{player.Name}는 {ASSET_NAME}를 소유하고 있습니다`)
else
print(`{player.Name}는 {ASSET_NAME}를 소유하고 있지 않습니다`)
end
end
Players.PlayerAdded:Connect(onPlayerAdded)Player Owns Bundle
Player Owns Bundle Async
반환
코드 샘플
번들 소유권 확인
local Players = game:GetService("Players")
local MarketplaceService = game:GetService("MarketplaceService")
-- 우리가 확인하고 있는 번들: https://www.roblox.com/bundles/589/Junkbot
local BUNDLE_ID = 589
local BUNDLE_NAME = "Junkbot"
Players.PlayerAdded:Connect(function(player)
local success, doesPlayerOwnBundle = pcall(function()
return MarketplaceService:PlayerOwnsBundleAsync(player, BUNDLE_ID)
end)
if success == false then
print("PlayerOwnsBundleAsync 호출 실패: ", doesPlayerOwnBundle)
return
end
if doesPlayerOwnBundle then
print(player.Name .. "은 " .. BUNDLE_NAME .. " 소유자입니다.")
else
print(player.Name .. "은 " .. BUNDLE_NAME .. " 소유자가 아닙니다.")
end
end)Prompt Bulk Purchase
매개 변수
반환
()
코드 샘플
대량 구매 클라이언트 프롬프트
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local promptBulkPurchaseEvent = ReplicatedStorage:WaitForChild("PromptBulkPurchaseEvent")
local part = Instance.new("Part")
part.Parent = workspace
local clickDetector = Instance.new("ClickDetector")
clickDetector.Parent = part
clickDetector.MouseClick:Connect(function()
promptBulkPurchaseEvent:FireServer({
{ Type = Enum.MarketplaceProductType.AvatarAsset, Id = "16630147" },
{ Type = Enum.MarketplaceProductType.AvatarBundle, Id = "182" },
})
end)대량 구매 프롬프트 서버
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local MarketplaceService = game:GetService("MarketplaceService")
local promptBulkPurchaseEvent = Instance.new("RemoteEvent")
promptBulkPurchaseEvent.Name = "PromptBulkPurchaseEvent"
promptBulkPurchaseEvent.Parent = ReplicatedStorage
-- 클라이언트에서 RemoteEvent가 발생하는 것을 듣고 대량 구매 프롬프트를 트리거합니다.
promptBulkPurchaseEvent.OnServerEvent:Connect(function(player, items)
MarketplaceService:PromptBulkPurchase(player, items, {})
end)시간 제한 옵션 구매 유도
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
local ASSET_ID = 105589844216517
Players.PlayerAdded:Connect(function(player)
local info = MarketplaceService:GetProductInfoAsync(ASSET_ID, Enum.InfoType.Asset)
if info.TimedOptions and #info.TimedOptions > 0 then
-- 가장 짧은 기간 옵션 찾기
local shortest = info.TimedOptions[1]
for _, option in info.TimedOptions do
if option.Duration < shortest.Duration then
shortest = option
end
end
local items = {
{
Type = Enum.MarketplaceProductType.AvatarAsset,
Id = tostring(ASSET_ID),
PurchaseOptions = {
{ Type = Enum.PurchaseOption.TimedOption, Value = shortest.Duration },
},
}
}
MarketplaceService:PromptBulkPurchase(player, items, {})
end
end)Prompt Bundle Purchase
Prompt Cancel Subscription
Prompt Game Pass Purchase
Prompt Premium Purchase
Prompt Product Purchase
Marketplace Service: Prompt Product Purchase(
):()
매개 변수
| 기본값: true |
| 기본값: Default |
반환
()
코드 샘플
MarketplaceService:PromptProductPurchase
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
local player = Players.LocalPlayer
local productId = 0000000 -- 이 값을 당신의 개발자 제품 ID로 변경하세요
-- 개발자 제품 구매를 요청하는 함수
local function promptPurchase()
MarketplaceService:PromptProductPurchase(player, productId)
end
promptPurchase()Prompt Purchase
Marketplace Service: Prompt Purchase(
):()
매개 변수
| 기본값: true |
| 기본값: Default |
반환
()
코드 샘플
로컬 스크립트 (클라이언트)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local promptPurchaseEvent = ReplicatedStorage:WaitForChild("PromptPurchaseEvent")
local part = Instance.new("Part")
part.Parent = workspace
local clickDetector = Instance.new("ClickDetector")
clickDetector.Parent = part
clickDetector.MouseClick:Connect(function()
promptPurchaseEvent:FireServer(16630147)
end)스크립트 (서버)
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local MarketplaceService = game:GetService("MarketplaceService")
local promptPurchaseEvent = Instance.new("RemoteEvent")
promptPurchaseEvent.Name = "PromptPurchaseEvent"
promptPurchaseEvent.Parent = ReplicatedStorage
-- 클라이언트에서 RemoteEvent가 발생하는 것을 듣고 구매 프롬프트를 트리거합니다.
promptPurchaseEvent.OnServerEvent:Connect(function(player, id)
MarketplaceService:PromptPurchase(player, id)
end)Prompt Roblox Subscription Purchase
매개 변수
반환
()
코드 샘플
로블록스 플러스 구독 구매 요청
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
local teleporter = script.Parent
local showModal = true
local EXCLUSIVE_AREA_POSITION = Vector3.new(1200, 200, 60)
-- 보상을 부여하고 구독하는 플레이어를 독점 지역으로 텔레포트합니다
local function grantRewardAndTeleport(player)
player:RequestStreamAroundAsync(EXCLUSIVE_AREA_POSITION)
local character = player.Character
if character and character.Parent then
local currentPivot = character:GetPivot()
character:PivotTo(currentPivot * CFrame.new(EXCLUSIVE_AREA_POSITION))
end
end
-- 캐릭터 부품이 텔레포터에 닿는 것을 감지합니다
teleporter.Touched:Connect(function(otherPart)
local player = Players:GetPlayerFromCharacter(otherPart.Parent)
if not player then
return
end
if not player:GetAttribute("CharacterPartsTouching") then
player:SetAttribute("CharacterPartsTouching", 0)
end
player:SetAttribute("CharacterPartsTouching", player:GetAttribute("CharacterPartsTouching") + 1)
if player.HasRobloxSubscription then
-- 플레이어는 이미 로블록스 플러스 구독 중입니다; 즉시 보상을 부여합니다
grantRewardAndTeleport(player)
else
-- 로블록스 플러스 구독을 요청합니다, 몇 초마다 한 번만 요청할 수 있습니다
if not showModal then
return
end
showModal = false
task.delay(5, function()
showModal = true
end)
MarketplaceService:PromptRobloxSubscriptionPurchase(player)
end
end)
-- 캐릭터 부품이 텔레포터에서 나가는 것을 감지합니다
teleporter.TouchEnded:Connect(function(otherPart)
local player = Players:GetPlayerFromCharacter(otherPart.Parent)
if player and player:GetAttribute("CharacterPartsTouching") then
player:SetAttribute("CharacterPartsTouching", player:GetAttribute("CharacterPartsTouching") - 1)
end
end)
-- 서버가 구독 변경을 확인할 때 보상을 부여합니다
-- 각 플레이어에 대해 HasRobloxSubscription 변경을 연결합니다
Players.PlayerAdded:Connect(function(player)
player:GetPropertyChangedSignal("HasRobloxSubscription"):Connect(function()
if player.HasRobloxSubscription
and player:GetAttribute("CharacterPartsTouching")
and player:GetAttribute("CharacterPartsTouching") > 0
then
grantRewardAndTeleport(player)
end
end)
end)Prompt Robux Transfer Async
반환
코드 샘플
MarketplaceService:PromptRobuxTransferAsync
local MarketplaceService = game:GetService("MarketplaceService")
-- 예제: 플레이어가 RemoteEvent를 트리거할 때 Robux 전송
local transferEvent = game.ReplicatedStorage:WaitForChild("RequestTransfer")
transferEvent.OnServerEvent:Connect(function(sender, receiverUserId, amount)
-- 입력 유효성 검사
if not sender or not sender:IsA("Player") then
return
end
if typeof(receiverUserId) ~= "number" or receiverUserId <= 0 then
warn("유효하지 않은 receiverUserId")
return
end
if typeof(amount) ~= "number" or amount <= 0 then
warn("유효하지 않은 금액")
return
end
local success, result = pcall(function()
return MarketplaceService:PromptRobuxTransferAsync(sender, receiverUserId, amount)
end)
if success then
print(`전송이 시작되었습니다. TransferRequestId: {result}`)
else
warn(`전송 실패: {result}`)
end
end)Prompt Subscription Purchase
Prompt VIP Server Purchase
매개 변수
반환
()
코드 샘플
VIP 서버 구매 프롬프트
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local buyButton = script.Parent
buyButton.Activated:Connect(function()
local success, errorMessage = pcall(function()
MarketplaceService:PromptVIPServerPurchase(localPlayer)
end)
if not success then
warn("VIP 서버 구매 프롬프트를 여는 데 실패했습니다:", errorMessage)
end
end)Rank Products Async
매개 변수
반환
{RankedItem}
코드 샘플
제공된 제품 ID를 기반으로 한 순위 제품 목록 가져오기
-- MarketplaceService를 가져옵니다.
local MarketplaceService = game:GetService("MarketplaceService")
-- 순위를 매기고 싶은 제품의 배열을 만듭니다.
local productIdentifiers = {
{InfoType = Enum.InfoType.GamePass, Id = 123},
{InfoType = Enum.InfoType.Product, Id = 456},
{InfoType = Enum.InfoType.Product, Id = 789}
}
-- 오류를 우아하게 처리하기 위해 보호된 호출로 호출합니다.
local success, rankedProducts = pcall(function()
return MarketplaceService:RankProductsAsync(productIdentifiers)
end)
if not success then
error("제품 순위 매기기 실패")
end
-- 반환된 항목을 상점에 로드합니다.
for i, rankedItem in ipairs(rankedProducts) do
local productIdentifier = rankedItem.ProductIdentifier
local productInfo = rankedItem.ProductInfo
print(productIdentifier, productInfo)
-- ...
-- 상점에 제품을 추가하는 로직
endRecommend Top Products Async
매개 변수
반환
{RankedItem}
코드 샘플
인게임 상점의 상위 제품 목록을 순위별로 가져오기
-- 마켓플레이스 서비스를 가져옵니다
local MarketplaceService = game:GetService("MarketplaceService")
-- 포함할 제품 유형의 배열을 만듭니다. 이 경우 게임 패스와 개발자 제품 모두 포함됩니다
local productTypes = {Enum.InfoType.GamePass, Enum.InfoType.Product}
-- 오류를 우아하게 처리하기 위해 보호된 호출을 사용합니다
local success, topRankedItems = pcall(function()
return MarketplaceService:RecommendTopProductsAsync(productTypes)
end)
if not success then
error("제품 순위 매기기 실패")
end
-- 반환된 항목을 상점에 로드합니다. 사용자가 더 이상 구매할 수 없는 개발자 제품과 같은 자격이 없는 항목을 topRankedItems에서 필터링해야 합니다
for i, rankedItem in ipairs(topRankedItems) do
local productIdentifier = rankedItem.ProductIdentifier
local productInfo = rankedItem.ProductInfo
print(productIdentifier, productInfo)
-- ...
-- 상점에 제품 추가하는 로직
endUser Owns Game Pass Async
반환
코드 샘플
투명 배칭을 사용한 여러 게임 패스 확인
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
local PASS_IDS = {1234567, 2345678, 3456789, 4567890}
local function checkPassesForPlayer(player: Player)
local owned = {}
local remaining = #PASS_IDS
local function check(passId)
local success, ownsPass = pcall(function()
return MarketplaceService:UserOwnsGamePassAsync(player.UserId, passId)
end)
if success and ownsPass then
table.insert(owned, passId)
end
remaining -= 1
end
-- 모든 호출을 동시에 생성하면 엔진이 이를 자동으로
-- 더 적은 HTTP 요청으로 배치합니다.
for _, passId in PASS_IDS do
task.spawn(check, passId)
end
while remaining > 0 do
task.wait()
end
return owned
end
Players.PlayerAdded:Connect(function(player)
local ownedPasses = checkPassesForPlayer(player)
print(player.Name, "은", #ownedPasses, "개의 패스를 소유하고 있습니다.")
end)이벤트
Prompt Bulk Purchase Finished
Marketplace Service. Prompt Bulk Purchase Finished(
매개 변수
Prompt Bundle Purchase Finished
Prompt Game Pass Purchase Finished
Marketplace Service. Prompt Game Pass Purchase Finished(
코드 샘플
게임패스 구매 완료 처리
local MarketplaceService = game:GetService("MarketplaceService")
local function gamepassPurchaseFinished(...)
-- 프롬프트의 모든 세부정보를 출력합니다. 예를 들어:
-- PromptGamePassPurchaseFinished PlayerName 123456 false
print("PromptGamePassPurchaseFinished", ...)
end
MarketplaceService.PromptGamePassPurchaseFinished:Connect(gamepassPurchaseFinished)Prompt Product Purchase Finished
Prompt Purchase Finished
Marketplace Service. Prompt Purchase Finished(
코드 샘플
PromptPurchaseFinished 이벤트 처리
local MarketplaceService = game:GetService("MarketplaceService")
local function onPromptPurchaseFinished(player, assetId, isPurchased)
if isPurchased then
print(player.Name, "아이템을 AssetID:", assetId, "로 구매했습니다.")
else
print(player.Name, "아이템을 AssetID:", assetId, "로 구매하지 않았습니다.")
end
end
MarketplaceService.PromptPurchaseFinished:Connect(onPromptPurchaseFinished)Prompt Roblox Subscription Purchase Finished
Marketplace Service. Prompt Roblox Subscription Purchase Finished(
코드 샘플
PromptRobloxSubscriptionPurchaseFinished 이벤트 처리
local MarketplaceService = game:GetService("MarketplaceService")
local function onPromptRobloxSubscriptionPurchaseFinished(player, didTryPurchasing)
if didTryPurchasing then
-- 플레이어가 구독을 시도했습니다; HasRobloxSubscription 변경을 기다려 확인
print(player.Name, "이 Roblox Plus 구독을 시도했습니다")
else
print(player.Name, "Roblox Plus 구독 프롬프트를 구매하지 않고 닫았습니다")
end
end
MarketplaceService.PromptRobloxSubscriptionPurchaseFinished:Connect(onPromptRobloxSubscriptionPurchaseFinished)콜백
Process Receipt
매개 변수
코드 샘플
영수증 처리 콜백
local MarketplaceService = game:GetService("MarketplaceService")
local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")
-- 성공적으로 처리된 구매를 추적하기 위한 데이터 저장소 설정
local purchaseHistoryStore = DataStoreService:GetDataStore("PurchaseHistory")
local productIdByName = {
fullHeal = 123123,
gold100 = 456456,
}
-- 제품 ID에 해당하는 구매를 승인하는 핸들러 함수를 조회하기 위한 사전
-- 이 함수들은 구매가 성공적으로 승인되면 true를 반환합니다
-- 이 함수들은 UpdateAsync() 콜백 내에서 나중에 호출되므로 절대 yield하면 안 됩니다
local grantPurchaseHandlerByProductId = {
[productIdByName.fullHeal] = function(_receipt, player)
local character = player.Character
local humanoid = character and character:FindFirstChild("Humanoid")
-- 플레이어가 치유할 수 있는 humanoid가 있는지 확인합니다
if not humanoid then
return false
end
-- 플레이어의 체력을 최대 체력으로 회복합니다
humanoid.Health = humanoid.MaxHealth
-- 성공적인 승인을 나타냅니다
return true
end,
[productIdByName.gold100] = function(_receipt, player)
local leaderstats = player:FindFirstChild("leaderstats")
local goldStat = leaderstats and leaderstats:FindFirstChild("Gold")
if not goldStat then
return false
end
-- 플레이어의 금 통계에 100 금을 추가합니다
goldStat.Value += 100
-- 성공적인 승인을 나타냅니다
return true
end,
}
-- 핵심 ProcessReceipt 콜백 함수
-- 이 구현은 대부분의 실패 시나리오를 처리하지만 교차 서버 데이터 실패 시나리오를 완전히 완화하지는 않습니다
local function processReceipt(receiptInfo)
local success, result = pcall(
purchaseHistoryStore.UpdateAsync,
purchaseHistoryStore,
receiptInfo.PurchaseId,
function(isPurchased)
if isPurchased then
-- 이 구매는 이미 승인된 것으로 기록되었으므로 이전에 처리되었어야 합니다
-- 구매를 두 번 승인하지 않도록 여기서 승인 핸들러를 호출하지 마십시오
-- 데이터 저장소의 값이 이미 true인 경우, true가 다시 반환되어 pcall 결과 변수도 true가 됩니다
-- 이는 나중에 영수증 프로세서에서 PurchaseGranted를 반환하는 데 사용됩니다
return true
end
local player = Players:GetPlayerByUserId(receiptInfo.PlayerId)
if not player then
-- 플레이어가 서버에 없으면 구매를 승인하지 않습니다
-- 그들이 재접속할 때 이 영수증 프로세서가 다시 호출됩니다
return nil
end
local grantPurchaseHandler = grantPurchaseHandlerByProductId[receiptInfo.ProductId]
if not grantPurchaseHandler then
-- 이 제품 ID에 대해 정의된 핸들러가 없으면 구매를 처리할 수 없습니다
-- 경험에서 판매되는 모든 제품 ID에 대해 핸들러가 설정되어 있는 한 이는 절대 발생하지 않습니다
warn(`제품 ID '{receiptInfo.ProductId}'에 대해 정의된 구매 핸들러가 없습니다`)
return nil
end
local handlerSucceeded, handlerResult = pcall(grantPurchaseHandler, receiptInfo, player)
if not handlerSucceeded then
local errorMessage = handlerResult
warn(
`'{player.Name}'가 제품 ID '{receiptInfo.ProductId}'의 구매를 처리하는 동안 구매 핸들러에서 오류가 발생했습니다: {errorMessage}`
)
return nil
end
local didHandlerGrantPurchase = handlerResult == true
if not didHandlerGrantPurchase then
-- 핸들러가 구매를 승인하지 않았으므로 승인되지 않은 것으로 기록합니다
return nil
end
-- 이제 구매가 플레이어에게 승인되었으므로 승인된 것으로 기록합니다
-- 이는 나중에 영수증 프로세서에서 PurchaseGranted를 반환하는 데 사용됩니다
return true
end
)
if not success then
local errorMessage = result
warn(`데이터 저장소 오류로 인해 영수증 처리에 실패했습니다: {errorMessage}`)
return Enum.ProductPurchaseDecision.NotProcessedYet
end
local didGrantPurchase = result == true
return if didGrantPurchase
then Enum.ProductPurchaseDecision.PurchaseGranted
else Enum.ProductPurchaseDecision.NotProcessedYet
end
-- 콜백을 설정합니다; 이는 서버의 하나의 스크립트에 의해 한 번만 수행될 수 있습니다
MarketplaceService.ProcessReceipt = processReceipt