Skip to content

Instantly share code, notes, and snippets.

@shaunidiot
Forked from tacyarg/chipsgg-docs.md
Created October 1, 2017 03:18
Show Gist options
  • Save shaunidiot/839f463c7922f9ec0690e6124706ec86 to your computer and use it in GitHub Desktop.
Save shaunidiot/839f463c7922f9ec0690e6124706ec86 to your computer and use it in GitHub Desktop.

CHIPS.GG API v1

User Authentication

All user authentication is handled using our auth service. Below is how you could use hosted user authentication.

SocketIO Interface

All socket calls can be made using this format.

socket.emit('action', 'listActions', {
  // add arguments
}, function(err, data){
    // do somthing...
})

HTTP POST Interface

All socket calls can be made using this format.

request({
  method: 'post',
  uri: `https://api.chips.gg/listActions`,
  body: {
    // add arguments
  },
  json: true
}).then(data => {
  // do somthing
})

appState

Synchronising with the backend state

getAppState

Returns the entire app state, this can be used with "stateSync" via listening to the "diff" event to handle realtime updates.

var socket = require('socket.io-client')('https://socket.chips.gg', {
    upgrade: false,
    transports: ['websocket', 'polling']
});
const store = require('store')
const state = require('statesync')(store.get('state'))

const getAppState = (state) => {
  return Promise.fromCallback(done => {
    socket.emit('action', 'getAppState', {}, done)
  })
}

socket.on('connect', function() {
  getAppState(state).then(done => {
    _.each(serverState, (value, key) => state.set(key, value))
    socket.on('diff', state.patch) // keep state up to date
  })
})

online

Returns the current online user count.

sendSupportEmail

Will send a email with the message specified to the support account. The recipient is specified in the .ENV file

  • email - email for the user
  • message - html message

listActions

List all available actions and endpoints

Notifications Service

getMyRecentNotifications

get all the logged in user's recent notifications

setNotificationRead

set the notification as read and delete from memory.

getMyUnreadNotifications

get all the users unread notifiactions.

SocketIO Events

  • notif.created - emitted once a notification has been created.
  • notif.read - emitted once a notification has been read.
socket.on('message', data => {
    if(data.event == 'notif.created'){
        console.log(data.message)
    }
})

Orders Service

Orders are actions that get completed in a series. They can trigger any number of internal functions based on if they complete or not.

getMyRecentOrders

get recent order history

SocketIO Events

  • order.created
  • order.complete
  • order.validate
  • order.failure
  • order.error
socket.on('message', data => {
    if(data.event == 'order.created'){
        console.log(data.message)
    }
})

Stats

getGameStatsUser

Fetch the users game stats by game type

  • gameType - OPTIONAL: The type of game. This can be found attached to the game object.

getGameStatsGlobal

Fetch the global stats by game type

  • gameType - OPTIONAL: The type of game. This can be found attached to the game object.

getIncomeStats

Fetch global income stats.

allStatsToday

Returns statstical data for the system in the past 24 hours.

Bank Accounts / Wallets

Secure transactional wallet system, can be used for whatever you desire, games, afiliates, points, ect. These will also be used for roulette and the partners internally.

getMyNonRedeemableWallet

get the user's non-redeemable wallet.

createWallet

Create credit wallet

  • walletid - wallet id OPTIONAL: This will return your main wallet if no id is provided."

getWallet

Get the specified wallet

  • walletid - wallet id OPTIONAL: This will return your main wallet if no id is provided."

getWalletTx

Get a specified tx

  • txid - transaction id

createMoney

Create the specified wallet credits

  • walletid - wallet id OPTIONAL: This will return your main wallet if no id is provided."
  • note - admin note.
  • value - value of generation.

destroyMoney

Destroy the specified wallet credits

  • walletid - wallet id OPTIONAL: This will return your main wallet if no id is provided."
  • note - admin note.
  • value - value to destroy.

getBankerID

Returns the admin system wallet.

transferCredits

Tranfer money from one wallet to another.

  • walletid - wallet id OPTIONAL: This will return your main wallet if no id is provided."
  • note - admin note.
  • value - value to destroy.

SocketIO Events

  • bank.created
  • bank.deposit
  • bank.withdraw
  • bank.transfer
socket.on('message', data => {
    if(data.event == 'bank.created'){
        console.log(data.message)
    }
})

Shop Service

convertItemCurrency

convert price to the current conversion rate.

  • currency - string: 'usd', 'credits'

getShopItems

Returns available items in the shop for users to buy using wallet credits.

  • currency - string: 'usd', 'credits'

marketWithdrawal

Send steam trade offer and deduct the credit value from the user's wallet.

Withdraw items into backpack. ( steam == false )
Withdraw items into steam. ( steam == true )
  • items - items to withdraw
  • steam - send from steam or backpack ( true/false )

marketDeposit

Request steam trade offer and credit the user's wallet.

Deposit items from backpack. ( steam == false )
Deposit items from steam. ( steam == true )
  • items - items to deposit
  • steam - send from steam or backpack ( true/false )

SocketIO Events

  • shop.created
  • shop.deposit
  • shop.withdraw
  • shop.refund
socket.on('message', data => {
    if(data.event == 'shop.created'){
        console.log(data.message)
    }
})

User Service

setUserVerified

Sets user verified status, used for influencers/partners. requires admin rank or greater

  • userid - the userid of the target

banUser

ban the specified user. requires admin rank or greater

  • userid - the userid of the target

unbanUser

unban the specified user. requires admin rank or greater

  • userid - the userid of the target

muteUser

mute the specified user. requires admin rank or greater

  • userid - the userid of the target
  • minutes - the number of minutes to mute the user. if no time is specified 60mis is the deafult

unmuteUser

unmute the specified user. requires admin rank or greater

  • userid - the userid of the target

findUser

find user by userid.

  • userid - userid

getUserWallets

get all the users active wallets.

listUserRanks

List the available user ranks available for use. Higher ranks are required to access protected functions.

setUserRank

Set the rank of the specified user. requires admin rank or greater

  • userid - the userid of the target

logout

Logout and invalidate the auth token. This token is required to make any calls that require user authentication.

me

Returns the authenticated userdata associated with the socket.

setToken

Sets the auth token recieved from the "/steam/login" post request (example above). This token is required to make any calls that require user authentication.

  • authToken - The token we got back in the post response.
//Example use.
// call will return the user object and allow private function calls using the token.
socket.emit('setToken', authToken, (err, data) => {
    if (err) {
        return console.log(err)
    }
    console.log('Authenticated:', data)
})

setTradeURL

Sets the tradeURL for the logged in user.

  • tradeurl - The trade url the user would like to save.

steamInventory

Returns the steam inventory for the authenticated user including prices.

getMyPackItems

Get backpack item contents.

depositMyPackItems

Deposit items from backpack, define onComplete/onFailure in params. ( steam == false )
Deposit items from steam into the backpack. ( steam == true )
  • items - items to withdraw
  • steam - send from steam or backpack ( true/false )

withdrawMyPackItems

Withdraw items from backpack, define onComplete/onFailure in params. ( steam == false )
Withdraw items from backpack into steam. ( steam == true )
  • items - items to withdraw
  • steam - send from steam or backpack ( true/false )

getMyTxHistory

this will return any transaction made using the banking system.

  • type - any type of tx that requires the bank. ( DEFAULT: 'privateTransfer' )

Chat Service

listChatRooms

list the room ids of all active rooms, returns an array of key strings. No parameters.

createRoom

Creates a new chat room

  • roomid - chat room id

removeRoom

Deletes specified chat room

  • roomid - chat room id

getChatCommands

Returns all the available chat commands

speak

send a message to a chat room. if no room specified just uses the default room. changes are reflected in the statesync object under the key path ['chats',roomid]. Rooms must be created explicitly before they can be used, currently that ability is not available.

  • message - the message to show in chat.
  • roomid - (optional) the room to send message to.

removeChatMessage

Removes chat message from chat room

  • messageid - the id of the message
  • roomid - the roomid that the message is in

getChatRoom

get the latest state of the chat room. if no room specified returns the default room. Use this to syncronize your state on first load.

  • roomid - (optional) the room to get the state of.

SocketIO Events

  • chat.created
  • chat.private
socket.on('message', data => {
    if(data.event == 'chat.created'){
        console.log(data.message)
    }
})

Coinflips Service

  • Watch the game.status for the current game state.
  • You can get the time left before state change by look at game[game.status]
    • In this object you will see two properties start and end.
      • start is the time this state started.
      • end is the time the state is planned to end.
  • TIP: as bets come in "state sync" updates the game object using this data we can display the game.

getCoinflipsHistoryUser

Get 100 of the most recent coinflips ordered by time created for the logged in user.

getRecentCoinflipsStats

Fetch the recent coinflips stats for the past 24 hours

  • name - name of the cfg for the COINFLIP

getCoinflipsUserStats

Gets how much the logged in user has bet/won in $

getRecentHistoricalCoinflips

Get the most recent coinflips completed.

  • name - The name of the config.
  • count - num of results you want. ( optional )

getCoinflipsConfig

Returns the config you requested.

createCoinflip

Sends the user a trade request for creating a coinflip.

Deposit items from backpack into the game. ( steam == false )
Deposit items from steam into the game. ( steam == true )
  • steam - send from steam or backpack ( true/false )
  • items - The items the user wants to join with.
  • selection - The side selection of the game, heads or tails

joinCoinflip

Sends the users a trade request to join an active game.

Deposit items from backpack into the game. ( steam == false )
Deposit items from steam into the game. ( steam == true )
  • steam - send from steam or backpack ( true/false )
  • gameid - The gameID of the specified active coinflip.
  • items - The items you would like to join with.
  • selection - The side selection of the game, heads or tails

getCoinflip

Returns the game object for the given gameid.

  • gameid - The id of the game.

cancelCoinflip

Attempts to cancel the active coinflip game

  • gameid - The id of the game

SocketIO Events

  • coinflip.created
  • coinflip.canceled
  • coinflip.joined
  • coinflip.ended
  • coinflip.rolling
socket.on('message', data => {
    if(data.event == 'coinflip.created'){
        console.log(data.message)
    }
})

Jackpots Service

  • Watch the game.status for the current game state.
  • You can get the time left before state change by look at game[game.status]
    • In this object you will see two properties start and end.
      • start is the time this state started.
      • end is the time the state is planned to end.
  • TIP: as bets come in "state sync" updates the game object using this data we can display the game.

getJackpotsUserStats

Gets how much the logged in user has bet/won in $

getRecentJackpotStats

Fetch the recent jackpot stats for the past 24 hours

  • name - name of the cfg for the jackpot

getRecentHistoricalJackpots

Get the most recent 5 jackpots by config name.

  • name - The name of the config.
  • count - num of results you want. ( optional )

getJackpotHistoryUser

Gets 100 of the most recent jackpots ordered by time created for the logged in user.

  • name - The name of the config.

getJackpotsConfig

Returns the config you requested.

findRunningGame

Fetch the current running game

  • name - name of the cfg for the game you want to find

joinJackpot

Sends the users a trade request to join an active game.

Deposit items from backpack into the game. ( steam == false )
Deposit items from steam into the game. ( steam == true )
  • steam - send from steam or backpack ( true/false )
  • items - The items you would like to join with.

getJackpot

Returns the game object for the given gameid.

  • gameid - The id of the game.

SocketIO Events

  • jackpot.created
  • jackpot.joined
  • jackpot.ended
  • jackpot.rolling
socket.on('message', data => {
    if(data.event == 'jackpot.created'){
        console.log(data.message)
    }
})

Roulette Service

  • Watch the game.status for the current game state.
  • You can get the time left before state change by look at game[game.status]
    • In this object you will see two properties start and end.
      • start is the time this state started.
      • end is the time the state is planned to end.
  • TIP: as bets come in "state sync" updates the game object using this data we can display the game.

getRecentRouletteHistory

Get most recent roulette game history

  • name - The name of the config.

getRouletteHistoryUser

Gets 100 of the most recent roulette games ordered by time created for the logged in user.

  • name - The name of the config.
  • count - num of results you want. ( optional )

getRouletteUserStats

Gets how much the logged in user has bet/won in credits

getRoulettesConfig

Returns the config you requested.

getSelections

Get the available roulette selections

joinRoulette

Attempt to join the specified roulette game, returns game

  • gameid - The id of the game.
  • value - The amount the user would like to spend.
  • selection - The bet selection.

getRoulette

Fetch game by id

  • gameid - the id of the game.

SocketIO Events

  • roulette.created
  • roulette.ended
  • roulette.rolling
  • roulette.joined
socket.on('message', data => {
    if(data.event == 'roulette.created'){
        console.log(data.message)
    }
})

Teamup Service

Teamup is a unique gammode mixing both jackpot and team based aspects. This game is designed to use credits. Players will play on thier choice of team. The team whos winning ticket is within the selected % range wins!

TeamupJoinRound

Join a teamup round.

  • team - the team the user wishes to join.
  • amount - the value of credits wagered.
  • secret - password to join team.

TeamupCreateTeam

Create a Teamup Team.

  • team - the team name.
  • amount - the value wagered.

TeamupUpdateConfig

Update current game service configuration. NOTE: each argument provided will be used as the config variable

TeamupPauseGame

Pause the current round.

  • pause - true/false

TeamupGetHistory

Get teamup game history.

TeamupGetGame

Get teamup game data.

TeamupGetStats

Get game stats.

SocketIO Events

  • teamup.created
  • teamup.ended
  • teamup.rolling
socket.on('message', data => {
    if(data.event == 'teamup.created'){
        console.log(data.message)
    }
})

Affiliates User Routes

This is the api to manage user affiliates and get data about each user and their affiliate codes.

createAffiliateCode

User must create a code before it can be used by anyone. Code needs to be unique, which you can check by calling affiliateCodeExists. Also since you want to create URL safe code, call slugify before code gets submitted to be created. There are several optional fields which the user can set, but by default it will create a normal code.

  • code - The affiliate code user wants to create
  • start (optional) The start date, Unix timestamp in MS, to when the code can start to be claimed
  • end (optional) The end date, Unix timestamp in MS, to when the code can no longer be claimed
  • limit (optional) The amount of times code can be claimed before being disabled
  • rake (optional) 0-1, The rake you will take for anyone using your code and signing up their own affiliates
  • details (optional) Any type of data you want to be associated with this code.

returns

See Affiliate Event Request Model.

setMyReferrer

User can set his referrer at any time, but is limited to changin it only once every 24 hours. This rate can be adjusted in the affiliates app.

  • code - The affiliate code user wants to join

returns

See Affiliate Event Request Model.

setAffiliateCodeRedeemable

Can temporarily disable or enable a code. It will not override any other limitations such as number of redemptions or start/end time. But can be used to temporarily prevent users from redeeming an active code.

  • code - The affiliate code user wants to create
  • isRedeemable - true or false. if true will allow the code to be redeemed. false will prevent anyone from redeeming.

returns

See Affiliate Event Request Model.

deactivateAffiliateCode

Permanently deactivaates code for this user. Allows code to be created again and claimed by a new user. Any past rewards will still go towards the previous user who deactivated the code. The code will still be visible in user statistics. This action cannot be undone, but if done by accident the user can immediately recreate the code to reclaim it if noone else has taken it.

  • code - The affiliate code user wants to deactivate.

returns

See Affiliate Event Request Model.

affiliateCodeExists

Check if the current code exists. You will need to slugify all codes before checking.

  • code - The code to check uniqueness of

returns

True or false

listMyAffiliateRequests

Returns a historical list of every action you have taken, creating codes, changing your referrer, etc.

returns

Array of Event Request Models

slugify

Turn code into URL safe "slug" which you can append to some url.

  • string or code - String to slugify

returns

URL safe code.

getMyAffiliateStats

Returns just the stats for the user requesting them

returns

See Affiliates User Model

Affiliates Admin Routes

Affiliate actions only admins can take.

listUserAffiliateRequests

Returns a historical list of every action a user has taken, creating codes, chanigner your referrer, etc. Only for admins

returns

Array of Event Request Models

updateAffiliateCode

This can update any code, mainly would be use to disabled codes by setting active:false.

  • code - The code you want to update
  • update - An object you want merged into the code.

returns

See Affiliate Event Request Model. You must poll for the state of the request.

giveUserScore

Gives a user an arbitrary score, positive or negative. Reward or punish users. Currently the system will manage assigning scores, admins should not need to use this.

  • userid - The user who is being updated
  • namespace - The affiliate namespace you want to apply score to.
  • amount - Amount of score to give user, positive adds, negative subtracts
  • details - Any kind of data you want to provide along with this action

returns

See Affiliate Event Request Model. You must poll for the state of the request.

getAffiliateStats

Gets all stats globally for the default affiliate namespace. All users, all codes.

returns

See Affiliate Stats Model.

checkAffiliateRequest

Checks a request you made. Each request has a requestid property. Use thie to check the state. Will return an object, if the "processed" property is true, then it has been processed and will eitehr haev an errror message or it succeeded.

  • requestid - The request id of the request you made previously.

returns

See Event Request Model

disableAffiliate

Disable a user from participating in affiliate schemes, cant make codes or collect rewards.

  • playerid - The user who is being disabled

returns

See Event Request Model

enableAffiliate

Enable a user to participate in affiliate schemes.

  • playerid - The user who is being enabled

returns

See Event Request Model

Affiliate Models

These models exist as part of the whole affiliate model which gets returned when you query or call stats.

Affiliate Model

This is the main model you deal with when looking at affiliate data.

Affiliates {
  constants:Constants;  //See constants model
  reward: number;       //total rewards earned
  start: number;        //first event date
  end: number;          //most recent event date
  duration: number;     //time between start and end
  ownership: Ownership; //Shows who currently owns what codes, see ownership model
  users: Users;         //See user model. all users and their stats

}

Users Model

Affiliates have a users model attached to the users property. Its a map of all users seen and thier stats, codes. etc.

Users {
  [userid:string]:User //See user model for details for details
}

User Model

Each user is attached by key to the affiliate model on the users property

User {
  id: string;                     //users id
  score: number;                  //score which is set through updateScore. not useful to user to see, used internally.
  reward: number;                 //rewards earned from users affiliates.
  paid: number;                   //amount user has paid to his referrers.
  profit: number;                 //$ amount in profit user has been paid.
  percent: number;                //percent of total pie the user has earned through his rewards
  isDisabled: boolean;            //is user disabled
  lastReferralChange: number;     //last time user has changed his referrer
  referralUser: string | null;    //the last user who has referred this user
  referralCode: string | null;    //the last code the user has redeemed
  referralCodes: CodeStats;       //stats for codes the user has redeemed. See code stats object.
  affiliateCodes: AffiliateCodes; //Stats for users affiliate codes. See affiliatecodes object.
}

AffiliateCodes Model

Attached to each user in an object which contains affiliate codes. These are codes the user has created himself in order to refer other users. Affiliate codes gain money for the user.

AffiliateCodes {
  [code:string]:Code;    //code id and the details of the code
}

Code Model

Any time there a new affiliate code is created, this object describes the code.

 Code {
  id: string;            //code id, the string it is redeemed with
  userid: string;        //userid, of the user who created code
  users: UserStats;      //stats of all users who have redeemed code, see UserStats model      
  rake: number;          //% rake, between 0 and 1
  maxUses: number;       //max nubmer of times code can be redeemed
  uses: number;          //number of times code has been redeemed
  start: number;         //timestamp of the code should be redeemable
  end: number;           //tiemstamp of when code should no longer be redeemable
  reward: number;        //total rewards this code has earned for the user who made it
  percent: number;       //Percent this code has contributed to your total percent for user.
  created: number;       //timestamp of when code was create
  updated: number;       //timestamp of when code was last changed
  isPublic: boolean;     //publicly visible
  isRedeemable: boolean; //can be redeemed by users
  isActive: boolean;     //no longer in use, another user can claim code
}                  

Codes User Stats Model

An object of user ids, each represening who has claimed this affiliate code, and how much they have earned for the creator.

UserStats {
  [id:string]:number;  //user id and the value user has generated
}

Referral Codes Stats Model

Attached to each user in an object which contains referral codes. These are codes the user has used as a reference at some point in time. A user can only have 1 referrer for a given time, but can change that at any time.

CodeStats {
  [code:string]:number; //Each code is keyed by code id. The value is how much score the user has given to his referrer
}                 

Ownership model

Just maps a code id to a user id. Shows who the current owner is. Users can deactivate codes to release ownership. Attached to the main affiliates object on the ownership property. o

Ownership {
  [code:string]:string;  //code and userid of user who owns code
}

Constants Model

This represents some constants to use when some data isnt provided.

Constants {
  defaultUser: string;         //default userid. DEFAULT_USER if not specified.
  defaultCode: string;         //default code. DEFAULT_CODE if not specified.                      
  defaultRake: number;         //default rake. No rake if not specified.
  maxActiveCodes: number;      //max active codes. Infinity if not specified.
  changeCodeRate: number;      //default change code rate, 24 hours if not specified.
}

Event Request Model

Any time you make a request to set/update/etc to an affiliate or code. You get back an object with request id. You need to query the server to see if your request was handled.

EventRequest {
  processed: boolean;    //whether this request has been processed,
  error: string;         //Usually a string explainign what went wrong wtih the request, if there was any. This should be shown to user.
  requestid: string;     //A unique id to request the status of this event.
  type: string;          //The type of request which was made
  namespace: string;     //The name you gave your affiliate scheme,
  //other data associated with the original request
}

Proving Games

Each game type has a corresponding provble hash series. For jackpots, there is a main and 30max, for coin flips there is just coinflip, for roulette there is roulette_main. You can request the hashes and outcomes of all historical games to be displayed in order, in a table for users to view. Below are the routes to get hashes/outcoes for each game type:

/listJackpotProvables

/list30MaxProvables

/listCoinflipProvables

/listRoulettelProvables

params

  • limit default 100, but you can specifiy a limit of games to be returned.

returns

This will return an array of provable data from the games, sorted from most recent to oldest.

[
  {
    gameid:string  //game id of game this outcome was generated on. you will need to query the game independantly to get game details
    hash:string    //the hash of the game. this should be displayed prominently. it will be shown in the third party site.
    outcome:number //the outcome of the game. this should be displayed prominently. it will be verified in a third party site. Depending on game type you may want to multiply by 100 before viewing
    time:timestamp //unix time in ms of when the outcome was generated
    type:string    //the game name
  }
  ...
]

** Test Calls **

These calls are ment to be used during development to better understand how the api works.

runNotificationTest

create a test notification.

runChatTest

speak in chat.

makeitrain

give yourself money.

Socket Events

These will be emitted by various services to notify you of lifecycle changes, these can be used to keep various frontend state up to date in realtime.

onlineUpdate

Emitted each time the socket connection count changes.

diff

Emitted each time a change happens on the server in state.

message

Emitted each time a client gets a private message from the server. Each message will be tagged with a type attribute from the list below.

.env

LOG_LEVEL= verbose

NODE_ENV= development
NODE_APPNAME= chipsgg

SOCKET_ORIGINS= 
SOCKET_PORT= 4501

DB_HOST= 
DB_PORT= 
DB_NAME= 
DB_USER= 
DB_PASS= 

REDIS_HOST= 
REDIS_PORT= 
REDIS_PASS= 

EXPRESS_SECRET= 
EXPRESS_PORT= 4500

DIRECT_LOGIN= 
DIRECT_PASSWORD=                        
DIRECT_TOKEN= 
DIRECT_URL= https://api.csgodirect.com
AUTH_URL= https://auth.csgodirect.com

AFFILIATES_URL= http://localhost:4555
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment