Skip to content

Instantly share code, notes, and snippets.

@banduk
Created June 18, 2020 11:20
Show Gist options
  • Save banduk/16e958dc4184346966416451e4bb66c8 to your computer and use it in GitHub Desktop.
Save banduk/16e958dc4184346966416451e4bb66c8 to your computer and use it in GitHub Desktop.
Mixpanel Push
# https://developer.mixpanel.com/docs/ios-push-notifications#importing-device-tokens
MIXPANEL_TOKEN = ""
def get_distinct_id(user_id)
user_id
end
def to_hex(s)
# s.unpack('U'*s.length).collect{|x| x.to_s 16}.join
s.unpack('H*').first
end
def get_tokens(user_id, platform)
mixpanel_tokens = { "$#{platform}_devices": [] }
push_tokens = PushToken.where(user_id: user_id, os: platform)
push_tokens.each do |push_token|
mixpanel_tokens[:"$#{push_token.os}_devices"] << to_hex(push_token.token)
end
return mixpanel_tokens
end
def mixpanel_token
raise StandardError, "MIXPANEL_TOKEN not defined", unless MIXPANEL_TOKEN.present?
MIXPANEL_TOKEN
end
def get_data(distinct_id, platform, tokens)
data = {
'$distinct_id': distinct_id,
'$token': mixpanel_token,
'$ignore_time': true,
'$union': tokens,
}
if platform == 'android'
data.merge!(
'$ip': "0",
)
end
data
end
def encode_data(data)
Base64.urlsafe_encode64(data.to_json, padding: true)
end
def url(data)
"http://api.mixpanel.com/engage/?data=#{data}"
end
def add_tokens(encoded_data)
RestClient::Request.execute(
method: :get,
url: url(encoded_data),
# headers: { params: { data: encoded_data } },
)
end
def add_token_to_mixpanel_user(user_id, platform)
distinct_id = get_distinct_id(user_id)
tokens = get_tokens(user_id, platform)
data = get_data(distinct_id, platform, tokens)
puts '---------------- data'
puts data.to_json
encoded_data = encode_data(data)
puts '---------------- encoded_data'
puts encoded_data
add_tokens(encoded_data)
end
# add_token_to_mixpanel_user('e7ae687d-295f-4fcf-8f28-3d4cdcbc654c') # jess
# add_token_to_mixpanel_user('5d36187a-0886-4812-a872-bc7e6f2738fc', 'ios') # banduk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment