Created
March 6, 2017 12:48
-
-
Save mhulet/9f55873835a023558770f098df376da8 to your computer and use it in GitHub Desktop.
Add Kustomer to a Rails 4 app with existing users
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# db/migrate/20170305194935_add_kustomer_id_to_users.rb | |
class AddKustomerIdToUsers < ActiveRecord::Migration | |
def change | |
add_column :users, :kustomer_id, :string | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Q: How should I create my Kustomer API key? | |
I don't know exactly which roles are required for the API key. Here is how I did it. | |
1. Go to https://APPNAME.kustomerapp.com/app/settings/api_keys | |
2. Create an API key with these roles: org.admin, org.user, org.admin.user, org.tracking, org.hooks | |
Q: How can I get the Secret key required for signing the JWT? | |
$ curl -X GET -H "Authorization: Bearer YOUR_KUSTOMER_API_KEY" -H "Cache-Control: no-cache" "https://api.kustomerapp.com/v1/auth/customer/settings" | |
The secret key you are looking for is in ['data']['attributes']['secret'] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/ app/views/layouts/snippets/_kustomer.html.slim | |
javascript: | |
!function(a,b,c,d){a.Kustomer=c,c._q=[],c._i=[],c.init=function(a){function b(a,b){a[b]=function(){a._q.push([b].concat(Array.prototype.slice.call(arguments,0)))}}for(var d="init clear identify track start describe".split(" "),e=0;e<d.length;e++)b(c,d[e]);c._i.push(a)};var e=b.createElement("script");e.type="text/javascript",e.async=!0,e.src="https://cdn.kustomerapp.com/cw/sdk.v1.min.js";var f=b.getElementsByTagName("script")[0];f.parentNode.insertBefore(e,f)}(this,document,window.Kustomer||{}); | |
Kustomer.init(ENV['KUSTOMER_API_KEY']); | |
- if user_signed_in? | |
javascript: | |
var kustomerJWT = KJUR.jws.JWS.sign( | |
'HS256', | |
{ | |
alg: 'HS256', | |
typ: 'JWT' | |
}, | |
{ | |
'externalId': '#{current_user.id}', | |
'iat': new Date().getTime() | |
}, | |
{ | |
'utf8': '#{ENV['KUSTOMER_SECRET_KEY']}' | |
} | |
); | |
Kustomer.identify(kustomerJWT); | |
javascript: | |
Kustomer.start(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/assets/javascripts/admin.coffee | |
//= require jsrsasign/jsrsasign-latest-all-min |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/ app/views/layouts/admin.html.slim | |
#sidebar | |
= link_to "Logout", destroy_company_user_session_path, method: :delete, onclick: "Kustomer.clear();" | |
- if Rails.env.production? | |
= render partial: "layouts/snippets/kustomer" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "appName", | |
"dependencies": { | |
"jsrsasign": "6.2.0" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# lib/tasks/kustomer.rake | |
# I just needed something that was working for the setup. This could be way better! | |
require "uri" | |
require "net/http" | |
namespace :kustomer do | |
task :create_customers => :environment do | |
url = URI("https://api.kustomerapp.com/v1/customers") | |
http = Net::HTTP.new(url.host, url.port) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
User.where.not(company: nil).each do |user| | |
next if user.company.nil? | |
request = Net::HTTP::Post.new(url) | |
request["authorization"] = "Bearer #{ENV['KUSTOMER_API_KEY']}" | |
request["content-type"] = "application/json" | |
request.body = { | |
"name": user.name, | |
"company": user.company.name, | |
"externalId": user.id.to_s, | |
"signedUpAt": user.created_at.iso8601, | |
"lastSeenAt": (user.current_sign_in_at.iso8601 rescue nil), | |
"emails": [ | |
{ | |
"email": user.email | |
} | |
], | |
"custom": { | |
"companyPlanStr": user.company.plan.name, | |
"companyRevenueNum": (user.company.plan.amount/100).to_i, | |
"companyReferralStr": user.company.referral, | |
"signInCountNum": user.sign_in_count, | |
"accountCreatorBool": user.id == user.company.users.pluck(:id).min | |
} | |
}.to_json | |
response = http.request(request) | |
puts response.read_body | |
end | |
end | |
task :set_kustomer_id_for_customers => :environment do | |
(1..3).each do |page| | |
url = URI("https://api.kustomerapp.com/v1/customers?page=#{page}") | |
http = Net::HTTP.new(url.host, url.port) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
request = Net::HTTP::Get.new(url) | |
request["authorization"] = "Bearer #{ENV['KUSTOMER_API_KEY']}" | |
request.body = "{}" | |
response = JSON.parse(http.request(request).read_body) | |
response['data'].each do |customer_json_response| | |
begin | |
user = User.find(customer_json_response['attributes']['externalId']) | |
next if user.nil? | |
user.update_column(:kustomer_id, customer_json_response['id']) | |
rescue; end | |
end | |
end | |
end | |
task :update_customers => :environment do | |
(1..3).each do |page| | |
url = URI("https://api.kustomerapp.com/v1/customers?page=#{page}") | |
http = Net::HTTP.new(url.host, url.port) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
request = Net::HTTP::Get.new(url) | |
request["authorization"] = "Bearer #{ENV['KUSTOMER_API_KEY']}" | |
request.body = "{}" | |
response = JSON.parse(http.request(request).read_body) | |
response['data'].each do |customer_json_response| | |
begin | |
user = User.find(customer_json_response['attributes']['externalId']) | |
next if user.nil? | |
url = URI("https://api.kustomerapp.com/v1/customers/#{user.kustomer_id}") | |
http = Net::HTTP.new(url.host, url.port) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
request = Net::HTTP::Patch.new(url) | |
request["authorization"] = "Bearer #{ENV['KUSTOMER_API_KEY']}" | |
request["content-type"] = "application/json" | |
request.body = { | |
"name": user.name, | |
"company": user.company.name, | |
"externalId": user.id.to_s, | |
"signedUpAt": user.created_at.iso8601, | |
"lastSeenAt": (user.current_sign_in_at.iso8601 rescue nil), | |
"emails": [ | |
{ | |
"email": user.email | |
} | |
], | |
"custom": { | |
"companyPlanStr": user.company.plan.name, | |
"companyRevenueNum": (user.company.plan.amount/100).to_i, | |
"companyReferralStr": user.company.referral, | |
"signInCountNum": user.sign_in_count, | |
"accountCreatorBool": user.id == user.company.users.pluck(:id).min | |
} | |
}.to_json | |
response = http.request(request) | |
puts response.read_body | |
rescue; end | |
end | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/jobs/kustomer_create_customer_job.rb | |
class KustomerCreateCustomerJob < BaseJob | |
def perform(user_id) | |
user = User.find(user_id) | |
url = URI("https://api.kustomerapp.com/v1/customers") | |
http = Net::HTTP.new(url.host, url.port) | |
http.use_ssl = true | |
http.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
user_external_id = Rails.env.development? ? "dev-#{user_id}" : user_id.to_s | |
request = Net::HTTP::Post.new(url) | |
request["authorization"] = "Bearer #{ENV['KUSTOMER_API_KEY']}" | |
request["content-type"] = "application/json" | |
request.body = { | |
"name": user.name, | |
"company": user.company.name, | |
"externalId": user_external_id, | |
"signedUpAt": user.created_at.iso8601, | |
"lastSeenAt": (user.current_sign_in_at.iso8601 rescue nil), | |
"emails": [ | |
{ | |
"email": user.email | |
} | |
], | |
"custom": { | |
"companyPlanStr": user.company.plan.name, | |
"companyRevenueNum": (user.company.plan.amount/100).to_i, | |
"companyReferralStr": user.company.referral, | |
"signInCountNum": user.sign_in_count, | |
"accountCreatorBool": user.id == user.company.users.pluck(:id).min | |
} | |
}.to_json | |
response = http.request(request) | |
puts "--------------------------------" | |
puts "Response received from Kustomer:" | |
puts response.read_body | |
puts "--------------------------------" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/controllers/users/registrations_controller.rb | |
class Users::RegistrationsController < Devise::RegistrationsController | |
def create | |
build_resource(sign_up_params) | |
resource.company.save if resource.valid? && resource.company.valid? | |
resource.save | |
yield resource if block_given? | |
if resource.persisted? | |
KustomerCreateCustomerJob.perform_later(resource.id) | |
# ... | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment