Need help with making a gamepass be rewarded when purchased mid-game

I have a seperate script making the gamepass activate when a player joins who has it, but i’m not sure how i can award this gamepass to someone when they’ve purchased it mid-game.

The gamepass in question gives the user a gravity coil

any help would be appreciated, thanks. This is the code i have so far, i have no idea what i’m supposed to be doing in this situation.

I removed the ID because this is sort of a secret project

script.Parent.MouseButton1Click:Connect(function()

local player = game.Players.LocalPlayer

if game:GetService('MarketplaceService'):UserOwnsGamePassAsync(player.userId, 00000000)
	then if player.Backpack:FindFirstChild("GravityCoil") == false then
		local grav = game.ReplicatedStorage.Gears.GravityCoil:Clone()
		grav.Parent = player.Backpack
else 

	local ms = game:GetService("MarketplaceService")
	ms:PromptProductPurchase(game.Players.LocalPlayer, 00000000)
end
end
end)

1 Like

If you’re attempting to make a button for a gamepass, then I’d recommend making a MouseButton1Click function with a remove event then prompting them with the gamepass - in which the remote will fire if the user has finished the prompt by using this code:

game.MarketplaceService.PromptGamePassPurchaseFinished:Connect(function()
game.ReplicatedStorage:WaitForChild("YOUR_REMOTE_EVENT"):FireServer()

After, a script that you implemented an OnServerEvent will check if they bought it and will reward it - but you’d need to create a function. For your scenario:

game.ReplicatedStorage:WaitForChild("YOUR_REMOTE_EVENT").OnServerEvent:Connect(function(plr)
local function gamepassPurchasedFinished(wasPurchased)
 if wasPurchased and game.MarketplaceService:UserOwnsGamePassAsync(plr.UserId, 000000) then -- if they have the gamepass then
-- stuff here
            end
         end
      end
   end
marketService.PromptGamePassPurchaseFinished:Connect(gamepassPurchasedFinished)
end)
2 Likes

Thank you! I will make sure to try this. appreciate the help

1 Like

Correction:

PromptGamePassPurchaseFinished takes 3 parameters: the Player object who bought the gamepass, the gamepass ID, and a bool which tells whether it was successfully purchased or was cancelled.

1 Like