學習
引擎類別
MarketplaceService
無法建立
服務

*此內容是使用 AI(Beta 測試版)翻譯,可能含有錯誤。若要以英文檢視此頁面,請按一下這裡


概要
方法
GetProductInfo(assetId: number,infoType: Enum.InfoType):Dictionary
已棄用
GetUsersPriceLevelsAsync(userIds: {any}):{PriceLevelInfo}
PlayerOwnsAsset(player: Instance,assetId: number):boolean
已棄用
PlayerOwnsBundle(player: Player,bundleId: number):boolean
已棄用
PromptBulkPurchase(player: Player,lineItems: {any},options: Dictionary):()
PromptBundlePurchase(player: Instance,bundleId: number):()
PromptCancelSubscription(user: Player,subscriptionId: string):()
PromptGamePassPurchase(player: Instance,gamePassId: number):()
PromptPremiumPurchase(player: Instance):()
已棄用
PromptProductPurchase(player: Instance,productId: number,equipIfPurchased: boolean,currencyType: Enum.CurrencyType):()
PromptPurchase(player: Instance,assetId: number,equipIfPurchased: boolean,currencyType: Enum.CurrencyType):()
PromptRobuxTransferAsync(sender: Player,receiverUserId: number,amount: number):string
PromptSubscriptionPurchase(user: Player,subscriptionId: string):()
RankProductsAsync(productIdentifiers: {any}):{RankedItem}
RecommendTopProductsAsync(infoTypes: {any}):{RankedItem}
繼承成員

API 參考
方法
BindReceiptHandler
功能: Monetization
MarketplaceService:BindReceiptHandler(
transactionType:Enum.ReceiptType, handler:function, filter:{any}?
參數
transactionType:Enum.ReceiptType
handler:function
filter:{any}?
範例程式碼
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
)

GetDeveloperProductsAsync
暫停
功能: AssetRead
MarketplaceService:GetDeveloperProductsAsync():Instance
返回
範例程式碼
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(" ")
end

GetProductInfo
已棄用

GetProductInfoAsync
暫停
功能: AssetRead
MarketplaceService:GetProductInfoAsync(
assetId:number, infoType:Enum.InfoType
參數
assetId:number
infoType:Enum.InfoType
預設值:"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 textLabel = script.Parent
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 羅布幣", days, option.Price))
end
end

GetRobloxSubscriptionDetailsAsync
暫停
功能: Monetization
MarketplaceService:GetRobloxSubscriptionDetailsAsync(user:Player):Dictionary
參數
user:Player
範例程式碼
檢查 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)

GetSubscriptionProductInfoAsync
暫停
功能: AssetRead
MarketplaceService:GetSubscriptionProductInfoAsync(subscriptionId:string):Dictionary
參數
subscriptionId:string

GetUsersPriceLevelsAsync
暫停
功能: Monetization
MarketplaceService:GetUsersPriceLevelsAsync(userIds:{any}):{PriceLevelInfo}
參數
userIds:{any}
返回
{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("無法檢索價格級別。")
end

GetUserSubscriptionDetailsAsync
暫停
功能: Monetization
MarketplaceService:GetUserSubscriptionDetailsAsync(
user:Player, subscriptionId:string
參數
user:Player
subscriptionId:string

GetUserSubscriptionPaymentHistoryAsync
暫停
功能: Monetization
MarketplaceService:GetUserSubscriptionPaymentHistoryAsync(
user:Player, subscriptionId:string
參數
user:Player
subscriptionId:string
返回
範例程式碼
MarketplaceService:獲取用戶訂閱付款歷史記錄
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)

GetUserSubscriptionStatusAsync
暫停
功能: Monetization
MarketplaceService:GetUserSubscriptionStatusAsync(
user:Player, subscriptionId:string
參數
user:Player
subscriptionId:string
範例程式碼
檢查用戶訂閱狀態
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)

PlayerOwnsAsset
已棄用

PlayerOwnsAssetAsync
暫停
功能: AssetRead
MarketplaceService:PlayerOwnsAssetAsync(
player:Instance, assetId:number
參數
player:Instance
assetId:number
返回
範例程式碼
檢查物品擁有權
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)

PlayerOwnsBundle
已棄用

PlayerOwnsBundleAsync
暫停
功能: AssetRead
MarketplaceService:PlayerOwnsBundleAsync(
player:Player, bundleId:number
參數
player:Player
bundleId:number
返回
範例程式碼
檢查附加包擁有權
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)

PromptBulkPurchase
功能: PromptExternalPurchase
MarketplaceService:PromptBulkPurchase(
player:Player, lineItems:{any}, options:Dictionary
):()
參數
player:Player
lineItems:{any}
options:Dictionary
返回
()
範例程式碼
提示批量購買客戶端
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)

PromptBundlePurchase
功能: PromptExternalPurchase
MarketplaceService:PromptBundlePurchase(
player:Instance, bundleId:number
):()
參數
player:Instance
bundleId:number
返回
()

PromptCancelSubscription
功能: PromptExternalPurchase
MarketplaceService:PromptCancelSubscription(
user:Player, subscriptionId:string
):()
參數
user:Player
subscriptionId:string
返回
()

PromptGamePassPurchase
功能: PromptExternalPurchase
MarketplaceService:PromptGamePassPurchase(
player:Instance, gamePassId:number
):()
參數
player:Instance
gamePassId:number
返回
()

PromptPremiumPurchase
已棄用

PromptProductPurchase
功能: PromptExternalPurchase
MarketplaceService:PromptProductPurchase(
player:Instance, productId:number, equipIfPurchased:boolean, currencyType:Enum.CurrencyType
):()
參數
player:Instance
productId:number
equipIfPurchased:boolean
預設值:true
currencyType:Enum.CurrencyType
預設值:"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()

PromptPurchase
功能: PromptExternalPurchase
MarketplaceService:PromptPurchase(
player:Instance, assetId:number, equipIfPurchased:boolean, currencyType:Enum.CurrencyType
):()
參數
player:Instance
assetId:number
equipIfPurchased:boolean
預設值:true
currencyType:Enum.CurrencyType
預設值:"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)

PromptRobloxSubscriptionPurchase
功能: PromptExternalPurchase
MarketplaceService:PromptRobloxSubscriptionPurchase(user:Player):()
參數
user:Player
返回
()
範例程式碼
提示 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)

PromptRobuxTransferAsync
暫停
功能: PromptExternalPurchase
MarketplaceService:PromptRobuxTransferAsync(
sender:Player, receiverUserId:number, amount:number
參數
sender:Player
receiverUserId:number
amount:number
返回
範例程式碼
MarketplaceService:PromptRobuxTransferAsync
local MarketplaceService = game:GetService("MarketplaceService")
local Players = game:GetService("Players")
-- 範例:當玩家觸發 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)

PromptSubscriptionPurchase
功能: PromptExternalPurchase
MarketplaceService:PromptSubscriptionPurchase(
user:Player, subscriptionId:string
):()
參數
user:Player
subscriptionId:string
返回
()

RankProductsAsync
暫停
MarketplaceService:RankProductsAsync(productIdentifiers:{any}):{RankedItem}
參數
productIdentifiers:{any}
返回
{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
-- ...
-- 邏輯將產品加入商店
end

RecommendTopProductsAsync
暫停
MarketplaceService:RecommendTopProductsAsync(infoTypes:{any}):{RankedItem}
參數
infoTypes:{any}
返回
{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
-- ...
-- 將產品添加到商店中的邏輯
end

UserOwnsGamePassAsync
暫停
功能: AssetRead
MarketplaceService:UserOwnsGamePassAsync(
userId:User, gamePassId:number
參數
userId:User
gamePassId:number
返回

活動
PromptBulkPurchaseFinished
功能: PromptExternalPurchase
MarketplaceService.PromptBulkPurchaseFinished(

PromptBundlePurchaseFinished
功能: PromptExternalPurchase
MarketplaceService.PromptBundlePurchaseFinished(
player:Instance, bundleId:number, wasPurchased:boolean
參數
player:Instance
bundleId:number
wasPurchased:boolean

PromptGamePassPurchaseFinished
功能: PromptExternalPurchase
MarketplaceService.PromptGamePassPurchaseFinished(
player:Instance, gamePassId:number, wasPurchased:boolean
參數
player:Instance
gamePassId:number
wasPurchased:boolean
範例程式碼
處理遊戲通行證購買完成
local MarketplaceService = game:GetService("MarketplaceService")
local function gamepassPurchaseFinished(...)
-- 列印提示的所有詳細信息, 例如:
-- PromptGamePassPurchaseFinished 玩家名稱 123456 false
print("PromptGamePassPurchaseFinished", ...)
end
MarketplaceService.PromptGamePassPurchaseFinished:Connect(gamepassPurchaseFinished)

PromptPremiumPurchaseFinished
功能: PromptExternalPurchase
MarketplaceService.PromptPremiumPurchaseFinished():RBXScriptSignal

PromptProductPurchaseFinished
功能: PromptExternalPurchase
MarketplaceService.PromptProductPurchaseFinished(
userId:number, productId:number, isPurchased:boolean
參數
userId:number
productId:number
isPurchased:boolean

PromptPurchaseFinished
功能: PromptExternalPurchase
MarketplaceService.PromptPurchaseFinished(
player:Instance, assetId:number, isPurchased:boolean
參數
player:Instance
assetId:number
isPurchased:boolean
範例程式碼
處理 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)

PromptRobloxSubscriptionPurchaseFinished
功能: PromptExternalPurchase
MarketplaceService.PromptRobloxSubscriptionPurchaseFinished(
user:Player, didTryPurchasing:boolean
參數
user:Player
didTryPurchasing:boolean
範例程式碼
處理 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)

PromptSubscriptionPurchaseFinished
功能: PromptExternalPurchase
MarketplaceService.PromptSubscriptionPurchaseFinished(
user:Player, subscriptionId:string, didTryPurchasing:boolean
參數
user:Player
subscriptionId:string
didTryPurchasing:boolean

回調
ProcessReceipt
功能: Monetization
MarketplaceService.ProcessReceipt(receiptInfo:Dictionary):Enum.ProductPurchaseDecision
參數
receiptInfo:Dictionary
範例程式碼
處理收據回調
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")
-- 確保玩家有一個人型可以治療
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

©2026 Roblox Corporation、Roblox、Roblox 標誌及 Powering Imagination 是我們在美國及其他國家地區的部分註冊與未註冊商標。