Skip to content

Instantly share code, notes, and snippets.

@rwillig
Created April 28, 2016 14:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwillig/3cf6328d8d2b7d80165de708bb31aec8 to your computer and use it in GitHub Desktop.
Save rwillig/3cf6328d8d2b7d80165de708bb31aec8 to your computer and use it in GitHub Desktop.
(ns ui.component.donate.stripe
(:require
[ui.core :as core :refer [donate-state donate-error]]
[clojure.set :as set :refer [rename-keys]]
[clojure.string :as s :refer [split]]))
(declare ensure-stripe stripe-init)
(def stripe-url "https://js.stripe.com/v2/")
(def key-mappings {:donor_address :address_line1
:donor_city :address_city
:donor_state :address_state
:donor_postalcode :address_zip
:card-number :number
:cvv :cvc})
(defc stripe-ready? false)
(defc stripe-loaded? false)
;(cell= (.log js/console "[stripe-loaded?]" stripe-loaded?))
;(cell= (.log js/console "[stripe-ready?]" stripe-ready?))
;(cell= (.log js/console "[stripe-public" (-> core/state :financial :credentials :stripe_public)))
(cell= (spy->> "[donate-error]" donate-error))
(add-watch core/state :stripe-load #(when (= (-> %4 :financial :provider) "stripe") (ensure-stripe)))
(add-watch stripe-loaded? :stripe-ready #(when %4 (stripe-init (-> @core/state :financial :credentials :stripe_public))))
(defn stripe-response-handler [action deferred donor status response]
(let [r (js->clj response :keywordize-keys true)
good (fn [d k r o n] (when (= (:donation_state n) "complete") (.resolve d)))
bad (fn [d k r o n] (when-not (nil? n) (.reject deferred)))]
(add-watch donate-state (keyword (gensym)) (partial good deferred))
(add-watch donate-error (keyword (gensym)) (partial bad deferred))
(if
(= status 200)
(action (merge donor {:token {:provider "stripe" :data (js->clj response :keywordize-keys true)}}))
(do
(reset! donate-error (ex-info (-> r :error :message) {}))))))
(defn get-stripe-token [action donor]
(let [[mo yr] (split (:card-expiration donor) #"/")
payload (assoc (rename-keys (select-keys donor (keys key-mappings)) key-mappings)
:exp_month mo
:exp_year yr)
d (.Deferred js/jQuery)
promise (.promise (js/jQuery "body"))]
(.createToken (.-card js/Stripe) (clj->js payload) (partial stripe-response-handler action d donor))
(.promise d)))
(defn stripe-init [pub-key]
(do
(.setPublishableKey js/Stripe pub-key)
(reset! stripe-ready? true)))
(defn ensure-stripe []
(.getScript js/jQuery stripe-url #(reset! stripe-loaded? true)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment