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のみにバインドされます。
-- フィルターを省略すると、フィルタリングされたハンドラーによって請求されていない任意の
-- 開発者製品の領収書に対して発火するキャッチオールハンドラーが登録されます。
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 = "Roblox Plus 割引",
}
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))透明バッチ処理を使用した並列 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
パラメータ
戻り値
コードサンプル
Roblox サブスクリプションの詳細を確認する
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)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
パラメータ
戻り値
()
コードサンプル
Roblox Plus サブスクリプション購入のプロンプト
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
-- プレイヤーはすでに Roblox Plus を持っています; 即座に報酬を付与
grantRewardAndTeleport(player)
else
-- Roblox Plus サブスクリプションを促す、数秒ごとにデバウンス
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")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- 例: プレイヤーが RemoteEvent をトリガーしたときに Robux を転送する
local transferEvent = 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}
コードサンプル
体験内ストアでの上位製品のランキング一覧を取得
-- MarketplaceServiceを取得する
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")
-- プレイヤーが回復するためのヒューマノイドを持っていることを確認します
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
-- この購入はすでに付与されたとして記録されているため、以前に処理されたはずです
-- 購入を2回付与しないように、ここで付与ハンドラを呼び出さないでください
-- データストアの値がすでに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
-- コールバックを設定します; これはサーバー上の1つのスクリプトによって1回だけ行うことができます
MarketplaceService.ProcessReceipt = processReceipt