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))顯示可用的計時選項
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平行獲取產品資訊的非透明批次處理
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 .. " 已訂閱,訂閱ID: " .. 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
參數
返回
()
範例程式碼
提示購買 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")
-- 範例:當玩家觸發 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}
範例程式碼
在您的體驗商店中獲取排名前列的產品清單
-- 獲取 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
-- 將返回的項目加載到商店中。確保過濾掉任何不合格的項目,例如用戶無法再購買的開發者產品
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
-- 這些函數絕不能產生 yield,因為它們稍後在 UpdateAsync() 回調中被調用
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