Skip to content

Instantly share code, notes, and snippets.

@pitluga
Created October 29, 2012 18:58
Show Gist options
  • Save pitluga/3975725 to your computer and use it in GitHub Desktop.
Save pitluga/3975725 to your computer and use it in GitHub Desktop.
Braintree Clojure Example
(ns braintree-clj.core
(:import [com.braintreegateway BraintreeGateway Environment TransactionRequest Transaction$Type])
(:require [clojure.string :as s]
[hiccup.core :as hiccup]
[hiccup.page-helpers :as page-helper]
[noir.core :as noir]
[noir.request :as noir-req]
[noir.server :as server]))
(def gateway (BraintreeGateway.
Environment/SANDBOX
"MERCHANT_ID",
"PUBLIC_KEY",
"PRIVATE_KEY"))
(defn layout [& content]
(page-helper/html5
[:head
[:title "Braintree-clj"]]
[:body
(hiccup/html content)]))
(defn checkout-form [data]
[:form {:method "POST" :action (-> gateway (.transparentRedirect) (.url))}
[:input { :type "hidden" :name "tr_data" :value (-> gateway (.transparentRedirect) (.trData (:tr-data data) "http://localhost:9888/confirm")) }]
[:label { :for "number" } "Credit Card Number"]
[:input { :id "number" :type "text" :name "transaction[credit_card][number]" :value (:number data) }]
[:br]
[:label { :for "expDate" } "Expiration Date"]
[:input { :id "expDate" :type "text" :name "transaction[credit_card][expiration_date]" :value (:exp-date data) }]
[:br]
[:input { :type "submit" :value "Checkout!"} ]])
(noir/defpage "/" []
(let [tr-data (-> (TransactionRequest.) (.amount (BigDecimal. "10.00")) (.type Transaction$Type/SALE))]
(views/layout
[:p "Your Cart:"]
[:ul
[:li "Wing Ding Qty: 1 Cost: $10.00"]]
(checkout-form {:tr-data tr-data}))))
(defn- render-success [tr-response]
"SUCCESS!")
(defn- render-errors [tr-response]
(prn (.getParameters tr-response))
(let [errors (-> tr-response (.getErrors) (.getAllDeepValidationErrors))
tr-data (-> (TransactionRequest.)
(.amount (BigDecimal. (-> tr-response (.getParameters) (get "transaction[amount]"))))
(.type (Transaction$Type/valueOf (s/upper-case (-> tr-response (.getParameters) (get "transaction[type]"))))))]
(views/layout
[:ul (map #(vector :li (format "%s: %s" (.getAttribute %) (.getMessage %))) errors)]
(checkout-form {:tr-data tr-data
:exp-date (-> tr-response (.getParameters) (get "transaction[credit_card][expiration_date]"))}))))
(noir/defpage "/confirm" []
(let [tr-response (-> gateway (.transparentRedirect) (.confirmTransaction (:query-string (noir-req/ring-request))))]
(if (.isSuccess tr-response)
(render-success tr-response)
(render-errors tr-response))))
(defn -main []
(server/start 9888))
(defproject braintree-clj "1.0.0-SNAPSHOT"
:description "Example braintree integration in clojure"
:repositories {"local" ~(str (.toURI (java.io.File. "repo")))}
:dependencies [[org.clojure/clojure "1.3.0"]
[braintree/braintree "2.15.0"]
[noir "1.2.2"]]
:main braintree-clj.core)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment