Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

0.3.0

  • Loading branch information...
commit fa8d8fbd0ee4fe26e54148091ebab6fd01779f09 1 parent b0aa020
@braintreeps braintreeps authored
Showing with 546 additions and 476 deletions.
  1. +1 −0  .gitignore
  2. +3 −1 Rakefile
  3. +13 −0 lib/braintree.coffee
  4. +5 −29 lib/braintree.js
  5. +5 −0 lib/braintree/address.coffee
  6. +18 −33 lib/braintree/address_gateway.coffee
  7. +6 −0 lib/braintree/attribute_setter.coffee
  8. +21 −0 lib/braintree/braintree_gateway.coffee
  9. +8 −9 lib/braintree/config.coffee
  10. +7 −7 lib/braintree/credit_card.coffee
  11. +18 −39 lib/braintree/credit_card_gateway.coffee
  12. +6 −7 lib/braintree/customer.coffee
  13. +18 −39 lib/braintree/customer_gateway.coffee
  14. +9 −11 lib/braintree/digest.coffee
  15. +6 −12 lib/braintree/environment.coffee
  16. +9 −10 lib/braintree/error_response.coffee
  17. +12 −6 lib/braintree/gateway.coffee
  18. +40 −34 lib/braintree/http.coffee
  19. +5 −0 lib/braintree/settlement_batch_summary.coffee
  20. +28 −0 lib/braintree/settlement_batch_summary_gateway.coffee
  21. +6 −7 lib/braintree/subscription.coffee
  22. +29 −49 lib/braintree/subscription_gateway.coffee
  23. +6 −7 lib/braintree/transaction.coffee
  24. +34 −51 lib/braintree/transaction_gateway.coffee
  25. +32 −44 lib/braintree/transparent_redirect_gateway.coffee
  26. +4 −5 lib/braintree/util.coffee
  27. +5 −6 lib/braintree/validation_error.coffee
  28. +29 −27 lib/braintree/validation_errors_collection.coffee
  29. +11 −15 lib/braintree/xml_parser.coffee
  30. +0 −1  node_modules/.bin/cake
  31. +0 −1  node_modules/.bin/coffee
  32. +0 −1  node_modules/.bin/vows
  33. +2 −2 package.json
  34. +2 −2 spec/braintree/braintree_spec.js
  35. +4 −4 spec/braintree/http_spec.js
  36. +111 −0 spec/braintree/settlement_batch_summary_gateway_spec.js
  37. +1 −1  spec/braintree/subscription_gateway_spec.js
  38. +5 −9 spec/braintree/transaction_gateway_spec.js
  39. +1 −1  spec/braintree/validation_errors_collection_spec.js
  40. +26 −6 spec/spec_helper.coffee
View
1  .gitignore
@@ -1,3 +1,4 @@
+/node_modules/.bin
/node_modules/coffee-script
/node_modules/o3-xml
/node_modules/underscore
View
4 Rakefile
@@ -2,5 +2,7 @@ task :default => :spec
desc "run the specs"
task :spec do
- sh "./node_modules/.bin/vows " + Dir.glob("spec/**/*_spec.js").join(" ")
+ local_vows = "./node_modules/.bin/vows"
+ vows = File.exist?(local_vows) ? local_vows : "vows"
+ sh "#{vows} " + Dir.glob("spec/**/*_spec.js").join(" ")
end
View
13 lib/braintree.coffee
@@ -0,0 +1,13 @@
+sys = require "sys"
+{Config} = require("./braintree/config")
+{Environment} = require("./braintree/environment")
+{BraintreeGateway} = require("./braintree/braintree_gateway")
+errorTypes = require("./braintree/error_types")
+
+connect = (config) ->
+ new BraintreeGateway(new Config(config))
+
+exports.connect = connect
+exports.version = '0.3.0'
+exports.Environment = Environment
+exports.errorTypes = errorTypes
View
34 lib/braintree.js
@@ -1,31 +1,7 @@
require('coffee-script');
+braintree = require('./braintree.coffee')
-var sys = require("sys"),
- Config = require("./braintree/config").Config,
- Environment = require("./braintree/environment").Environment,
- Gateway = require("./braintree/gateway").Gateway,
- AddressGateway = require("./braintree/address_gateway").AddressGateway,
- CreditCardGateway = require("./braintree/credit_card_gateway").CreditCardGateway,
- CustomerGateway = require("./braintree/customer_gateway").CustomerGateway,
- SubscriptionGateway = require("./braintree/subscription_gateway").SubscriptionGateway,
- TransactionGateway = require("./braintree/transaction_gateway").TransactionGateway,
- TransparentRedirectGateway = require("./braintree/transparent_redirect_gateway").TransparentRedirectGateway,
- errorTypes = require("./braintree/error_types");
-
-var connect = function(config) {
- var gateway = Gateway(Config(config));
- return {
- _gateway: gateway,
- address: AddressGateway(gateway),
- creditCard: CreditCardGateway(gateway),
- customer: CustomerGateway(gateway),
- subscription: SubscriptionGateway(gateway),
- transaction: TransactionGateway(gateway),
- transparentRedirect: TransparentRedirectGateway(gateway)
- };
-};
-
-exports.connect = connect;
-exports.version = '0.2.0';
-exports.Environment = Environment;
-exports.errorTypes = errorTypes;
+exports.connect = braintree.connect;
+exports.version = braintree.version;
+exports.Environment = braintree.Environment;
+exports.errorTypes = braintree.errorTypes;
View
5 lib/braintree/address.coffee
@@ -0,0 +1,5 @@
+{AttributeSetter} = require('./attribute_setter')
+
+class Address extends AttributeSetter
+
+exports.Address = Address
View
51 lib/braintree/address_gateway.coffee
@@ -1,43 +1,28 @@
-ErrorResponse = require('./error_response').ErrorResponse
+{Gateway} = require('./gateway')
+{Address} = require('./address')
-AddressGateway = (gateway) ->
- my = { gateway: gateway }
+class AddressGateway extends Gateway
+ constructor: (@gateway) ->
- create = (attributes, callback) ->
+ create: (attributes, callback) ->
customerId = attributes.customerId
delete(attributes.customerId)
- my.gateway.http.post("/customers/#{customerId}/addresses", {address: attributes}, responseHandler(callback))
+ @gateway.http.post("/customers/#{customerId}/addresses", {address: attributes}, @responseHandler(callback))
- destroy = (customerId, id, callback) ->
- my.gateway.http.delete("/customers/#{customerId}/addresses/#{id}", callback)
+ delete: (customerId, id, callback) ->
+ @gateway.http.delete("/customers/#{customerId}/addresses/#{id}", callback)
- find = (customerId, id, callback) ->
- callback = callback
- my.gateway.http.get("/customers/#{customerId}/addresses/#{id}" , (err, response) ->
- return callback(err, null) if err
- callback(null, response.address)
- )
+ find: (customerId, id, callback) ->
+ @gateway.http.get "/customers/#{customerId}/addresses/#{id}", (err, response) ->
+ if err
+ callback(err, null)
+ else
+ callback(null, response.address)
+ update: (customerId, id, attributes, callback) ->
+ @gateway.http.put("/customers/#{customerId}/addresses/#{id}", {address: attributes}, @responseHandler(callback))
- update = (customerId, id, attributes, callback) ->
- my.gateway.http.put("/customers/#{customerId}/addresses/#{id}", {address: attributes}, responseHandler(callback))
-
- responseHandler = (callback) ->
- return (err, response) ->
- return callback(err, response) if err
-
- if (response.address)
- response.success = true
- callback(null, response)
- else if (response.apiErrorResponse)
- callback(null, ErrorResponse(response.apiErrorResponse))
-
- {
- create: create,
- delete: destroy,
- find: find,
- update: update
- }
+ responseHandler: (callback) ->
+ @createResponseHandler("address", Address, callback)
exports.AddressGateway = AddressGateway
-
View
6 lib/braintree/attribute_setter.coffee
@@ -0,0 +1,6 @@
+class AttributeSetter
+ constructor: (attributes) ->
+ for key, value of attributes
+ @[key] = value
+
+exports.AttributeSetter = AttributeSetter
View
21 lib/braintree/braintree_gateway.coffee
@@ -0,0 +1,21 @@
+{Http} = require('./http')
+{AddressGateway} = require("./address_gateway")
+{CreditCardGateway} = require("./credit_card_gateway")
+{CustomerGateway} = require("./customer_gateway")
+{SettlementBatchSummaryGateway} = require("./settlement_batch_summary_gateway")
+{SubscriptionGateway} = require("./subscription_gateway")
+{TransactionGateway} = require("./transaction_gateway")
+{TransparentRedirectGateway} = require("./transparent_redirect_gateway")
+
+class BraintreeGateway
+ constructor: (@config) ->
+ @http = new Http(@config)
+ @address = new AddressGateway(this)
+ @creditCard = new CreditCardGateway(this)
+ @customer = new CustomerGateway(this)
+ @settlementBatchSummary = new SettlementBatchSummaryGateway(this)
+ @subscription = new SubscriptionGateway(this)
+ @transaction = new TransactionGateway(this)
+ @transparentRedirect = new TransparentRedirectGateway(this)
+
+exports.BraintreeGateway = BraintreeGateway
View
17 lib/braintree/config.coffee
@@ -1,11 +1,10 @@
-Config = (rawConfig) ->
- {
- apiVersion: '2',
- environment: rawConfig.environment,
- merchantId: rawConfig.merchantId,
- publicKey: rawConfig.publicKey,
- privateKey: rawConfig.privateKey,
- baseMerchantPath: '/merchants/' + rawConfig.merchantId
- }
+class Config
+ constructor: (rawConfig) ->
+ @apiVersion = '2'
+ @environment = rawConfig.environment
+ @merchantId = rawConfig.merchantId
+ @publicKey = rawConfig.publicKey
+ @privateKey = rawConfig.privateKey
+ @baseMerchantPath = "/merchants/#{rawConfig.merchantId}"
exports.Config = Config
View
14 lib/braintree/credit_card.coffee
@@ -1,9 +1,9 @@
-CreditCard = (attributes) ->
- that = {}
- for key, value of attributes
- that[key] = value
- that.maskedNumber = that.bin + '******' + that.last4
- that.expirationDate = that.expirationMonth + '/' + that.expirationYear
- that
+{AttributeSetter} = require('./attribute_setter')
+
+class CreditCard extends AttributeSetter
+ constructor: (attributes) ->
+ super attributes
+ @maskedNumber = "#{@bin}******#{@last4}"
+ @expirationDate = "#{@expirationMonth}/#{@expirationYear}"
exports.CreditCard = CreditCard
View
57 lib/braintree/credit_card_gateway.coffee
@@ -1,47 +1,26 @@
-CreditCard = require('./credit_card').CreditCard
-ErrorResponse = require('./error_response').ErrorResponse
+{Gateway} = require('./gateway')
+{CreditCard} = require('./credit_card')
-CreditCardGateway = (gateway) ->
- my = { gateway: gateway }
+class CreditCardGateway extends Gateway
+ constructor: (@gateway) ->
- create = (attributes, callback) ->
- my.gateway.http.post('/payment_methods', {creditCard: attributes}, responseHandler(callback))
+ create: (attributes, callback) ->
+ @gateway.http.post('/payment_methods', {creditCard: attributes}, @responseHandler(callback))
- destroy = (token, callback) ->
- my.gateway.http.delete('/payment_methods/' + token, callback)
+ delete: (token, callback) ->
+ @gateway.http.delete("/payment_methods/#{token}", callback)
- find = (token, callback) ->
- callback = callback
- my.gateway.http.get('/payment_methods/' + token, (err, response) ->
- return callback(err, null) if err
- callback(null, CreditCard(response.creditCard))
- )
+ find: (token, callback) ->
+ @gateway.http.get "/payment_methods/#{token}", (err, response) ->
+ if err
+ callback(err, null)
+ else
+ callback(null, new CreditCard(response.creditCard))
+ update: (token, attributes, callback) ->
+ @gateway.http.put("/payment_methods/#{token}", {creditCard: attributes}, @responseHandler(callback))
- update = (token, attributes, callback) ->
- my.gateway.http.put(
- '/payment_methods/' + token,
- {creditCard: attributes},
- responseHandler(callback)
- )
-
- responseHandler = (callback) ->
- return (err, response) ->
- return callback(err, response) if err
-
- if (response.creditCard)
- response.success = true
- response.creditCard = CreditCard(response.creditCard)
- callback(null, response)
- else if (response.apiErrorResponse)
- callback(null, ErrorResponse(response.apiErrorResponse))
-
- {
- create: create,
- delete: destroy,
- find: find,
- responseHandler: responseHandler,
- update: update
- }
+ responseHandler: (callback) ->
+ @createResponseHandler("creditCard", CreditCard, callback)
exports.CreditCardGateway = CreditCardGateway
View
13 lib/braintree/customer.coffee
@@ -1,10 +1,9 @@
-CreditCard = require('./credit_card').CreditCard
+{AttributeSetter} = require('./attribute_setter')
+{CreditCard} = require('./credit_card')
-Customer = (attributes) ->
- that = {}
- for key, value of attributes
- that[key] = value
- that.creditCards = (CreditCard(cardAttributes) for cardAttributes in attributes.creditCards)
- that
+class Customer extends AttributeSetter
+ constructor: (attributes) ->
+ super attributes
+ @creditCards = (new CreditCard(cardAttributes) for cardAttributes in attributes.creditCards)
exports.Customer = Customer
View
57 lib/braintree/customer_gateway.coffee
@@ -1,47 +1,26 @@
-Customer = require('./customer').Customer
-ErrorResponse = require('./error_response').ErrorResponse
+{Gateway} = require('./gateway')
+{Customer} = require('./customer')
-CustomerGateway = (gateway) ->
- my = { gateway: gateway }
+class CustomerGateway extends Gateway
+ constructor: (@gateway) ->
- create = (attributes, callback) ->
- my.gateway.http.post('/customers', {customer: attributes}, responseHandler(callback))
+ create: (attributes, callback) ->
+ @gateway.http.post('/customers', {customer: attributes}, @responseHandler(callback))
- destroy = (customer_id, callback) ->
- my.gateway.http.delete('/customers/' + customer_id, callback)
+ delete: (customerId, callback) ->
+ @gateway.http.delete("/customers/#{customerId}", callback)
- find = (customer_id, callback) ->
- callback = callback
- my.gateway.http.get('/customers/' + customer_id, (err, response) ->
- return callback(err, null) if err
- callback(null, Customer(response.customer))
- )
+ find: (customerId, callback) ->
+ @gateway.http.get "/customers/#{customerId}", (err, response) ->
+ if err
+ callback(err, null)
+ else
+ callback(null, new Customer(response.customer))
- update = (customer_id, attributes, callback) ->
- my.gateway.http.put(
- '/customers/' + customer_id,
- { customer: attributes },
- responseHandler(callback)
- )
+ update: (customerId, attributes, callback) ->
+ @gateway.http.put("/customers/#{customerId}", {customer: attributes}, @responseHandler(callback))
- responseHandler = (callback) ->
- (err, response) ->
- return callback(err, response) if err
-
- if (response.customer)
- response.success = true
- response.customer = Customer(response.customer)
- callback(null, response)
- else if (response.apiErrorResponse)
- callback(null, ErrorResponse(response.apiErrorResponse))
-
- {
- create: create,
- delete: destroy,
- find: find,
- responseHandler: responseHandler,
- update: update
- }
+ responseHandler: (callback) ->
+ @createResponseHandler("customer", Customer, callback)
exports.CustomerGateway = CustomerGateway
-
View
20 lib/braintree/digest.coffee
@@ -1,20 +1,18 @@
sys = require('sys')
crypto = require('crypto')
-Digest = ->
- sha1 = (data) ->
- hash = crypto.createHash('sha1')
- hash.update(data)
- hash.digest()
+class Digest
+ @hexdigest: (privateKey, string) ->
+ new Digest().hmacSha1(privateKey, string)
- hmacSha1 = (key, data) ->
- hmac = crypto.createHmac('sha1', sha1(key))
+ hmacSha1: (key, data) ->
+ hmac = crypto.createHmac('sha1', @sha1(key))
hmac.update(data)
hmac.digest('hex')
- { hmacSha1: hmacSha1 }
-
-Digest.hexdigest = (privateKey, string) ->
- Digest().hmacSha1(privateKey, string)
+ sha1: (data) ->
+ hash = crypto.createHash('sha1')
+ hash.update(data)
+ hash.digest()
exports.Digest = Digest
View
18 lib/braintree/environment.coffee
@@ -1,15 +1,9 @@
-Environment = (server, port, ssl) ->
- {
- server: server,
- port: port,
- ssl: ssl
- }
+class Environment
+ DEVELOPMENT_PORT = process.env['GATEWAY_PORT'] || '3000'
+ @Development = new Environment('localhost', DEVELOPMENT_PORT, false)
+ @Sandbox = new Environment('sandbox.braintreegateway.com', '443', true)
+ @Production = new Environment('www.braintreegateway.com', '443', true)
-
-developmentPort = process.env['GATEWAY_PORT'] || '3000'
-
-Environment.Development = Environment('localhost', developmentPort, false)
-Environment.Sandbox = Environment('sandbox.braintreegateway.com', '443', true)
-Environment.Production = Environment('www.braintreegateway.com', '443', true)
+ constructor: (@server, @port, @ssl) ->
exports.Environment = Environment
View
19 lib/braintree/error_response.coffee
@@ -1,13 +1,12 @@
-Transaction = require('./transaction').Transaction
-ValidationErrorsCollection = require('./validation_errors_collection').ValidationErrorsCollection
+{Transaction} = require('./transaction')
+{ValidationErrorsCollection} = require('./validation_errors_collection')
-ErrorResponse = (attributes) ->
- that = {}
- for key, value of attributes
- that[key] = value
- that.success = false
- that.errors = ValidationErrorsCollection(attributes.errors)
- that.transaction = Transaction(attributes.transaction) if attributes.transaction
- that
+class ErrorResponse
+ constructor: (attributes) ->
+ for key, value of attributes
+ @[key] = value
+ @success = false
+ @errors = new ValidationErrorsCollection(attributes.errors)
+ @transaction = new Transaction(attributes.transaction) if attributes.transaction
exports.ErrorResponse = ErrorResponse
View
18 lib/braintree/gateway.coffee
@@ -1,9 +1,15 @@
-Http = require('./http').Http
+{ErrorResponse} = require('./error_response')
-Gateway = (config) ->
- {
- config: config,
- http: Http(config)
- }
+class Gateway
+ createResponseHandler: (attributeName, klass, callback) ->
+ (err, response) ->
+ return callback(err, response) if err
+
+ if (response[attributeName])
+ response.success = true
+ response[attributeName] = new klass(response[attributeName])
+ callback(null, response)
+ else if (response.apiErrorResponse)
+ callback(null, new ErrorResponse(response.apiErrorResponse))
exports.Gateway = Gateway
View
74 lib/braintree/http.coffee
@@ -1,42 +1,67 @@
sys = require('sys')
http = require('http')
https = require('https')
-Buffer = require('buffer').Buffer
+{Buffer} = require('buffer')
braintree = require('../braintree')
-XmlParser = require('./xml_parser').XmlParser
+{XmlParser} = require('./xml_parser')
exceptions = require('./exceptions')
-Util = require('./util').Util
+{Util} = require('./util')
-Http = (config) ->
- my = { config: config }
+class Http
+ constructor: (@config) ->
+
+ checkHttpStatus: (status) ->
+ switch status.toString()
+ when '200', '201', '422' then null
+ when '401' then exceptions.AuthenticationError()
+ when '403' then exceptions.AuthorizationError()
+ when '404' then exceptions.NotFoundError()
+ when '426' then exceptions.UpgradeRequired()
+ when '500' then exceptions.ServerError()
+ when '503' then exceptions.DownForMaintenanceError()
+ else exceptions.UnexpectedError('Unexpected HTTP response: ' + status)
+
+ delete: (url, callback) ->
+ @request('DELETE', url, null, callback)
+
+ get: (url, callback) ->
+ @request('GET', url, null, callback)
+
+ post: (url, body, callback) ->
+ @request('POST', url, body, callback)
+
+ put: (url, body, callback) ->
+ @request('PUT', url, body, callback)
+
+ request: (method, url, body, callback) ->
+ client = if @config.environment.ssl then https else http
- request = (method, url, body, callback) ->
- client = if my.config.environment.ssl then https else http
options = {
- host: my.config.environment.server,
- port: my.config.environment.port,
+ host: @config.environment.server,
+ port: @config.environment.port,
method: method,
- path: my.config.baseMerchantPath + url,
+ path: @config.baseMerchantPath + url,
headers: {
- 'Authorization': (new Buffer(my.config.publicKey + ':' + my.config.privateKey)).toString('base64'),
- 'X-ApiVersion': my.config.apiVersion,
+ 'Authorization': (new Buffer(@config.publicKey + ':' + @config.privateKey)).toString('base64'),
+ 'X-ApiVersion': @config.apiVersion,
'Accept': 'application/xml',
'Content-Type': 'application/json',
'User-Agent': 'Braintree Node ' + braintree.version
}
}
+
if body
requestBody = JSON.stringify(Util.convertObjectKeysToUnderscores(body))
options.headers['Content-Length'] = requestBody.length.toString()
- theRequest = client.request(options, (response) ->
+ theRequest = client.request(options, (response) =>
body = ''
response.on('data', (responseBody) -> body += responseBody )
- response.on('end', ->
- error = checkHttpStatus(response.statusCode)
+ response.on('end', =>
+ error = @checkHttpStatus(response.statusCode)
return callback(error, null) if error
if body isnt ' '
callback(null, XmlParser.parse(body))
@@ -47,23 +72,4 @@ Http = (config) ->
theRequest.write(requestBody) if body
theRequest.end()
- checkHttpStatus = (status) ->
- switch status.toString()
- when '200', '201', '422' then null
- when '401' then exceptions.AuthenticationError()
- when '403' then exceptions.AuthorizationError()
- when '404' then exceptions.NotFoundError()
- when '426' then exceptions.UpgradeRequired()
- when '500' then exceptions.ServerError()
- when '503' then exceptions.DownForMaintenanceError()
- else exceptions.UnexpectedError('Unexpected HTTP response: ' + status)
-
- {
- checkHttpStatus: checkHttpStatus,
- delete: (url, callback) -> request('DELETE', url, null, callback)
- get: (url, callback) -> request('GET', url, null, callback)
- post: (url, body, callback) -> request('POST', url, body, callback)
- put: (url, body, callback) -> request('PUT', url, body, callback)
- }
-
exports.Http = Http
View
5 lib/braintree/settlement_batch_summary.coffee
@@ -0,0 +1,5 @@
+{AttributeSetter} = require('./attribute_setter')
+
+class SettlementBatchSummary extends AttributeSetter
+
+exports.SettlementBatchSummary = SettlementBatchSummary
View
28 lib/braintree/settlement_batch_summary_gateway.coffee
@@ -0,0 +1,28 @@
+{Gateway} = require('./gateway')
+{Util} = require('./util')
+{SettlementBatchSummary} = require('./settlement_batch_summary')
+
+class SettlementBatchSummaryGateway extends Gateway
+ constructor: (@gateway) ->
+
+ generate: (criteria, callback) ->
+ @gateway.http.post(
+ "/settlement_batch_summary",
+ {settlementBatchSummary: criteria},
+ @responseHandler(criteria, callback)
+ )
+
+ responseHandler: (criteria, callback) ->
+ @createResponseHandler "settlementBatchSummary", SettlementBatchSummary, (err, response) =>
+ callback(null, @underscoreCustomField(criteria, response))
+
+ underscoreCustomField: (criteria, response) ->
+ if response.success and ('groupByCustomField' of criteria)
+ camelCustomField = Util.toCamelCase(criteria.groupByCustomField)
+ for record in response.settlementBatchSummary.records
+ record[criteria.groupByCustomField] = record[camelCustomField]
+ record[camelCustomField] = null
+
+ response
+
+exports.SettlementBatchSummaryGateway = SettlementBatchSummaryGateway
View
13 lib/braintree/subscription.coffee
@@ -1,10 +1,9 @@
-Transaction = require('./transaction').Transaction
+{AttributeSetter} = require('./attribute_setter')
+{Transaction} = require('./transaction')
-Subscription = (attributes) ->
- that = {}
- for key, value of attributes
- that[key] = value
- that.transactions = (Transaction(transactionAttributes) for transactionAttributes in attributes.transactions)
- that
+class Subscription extends AttributeSetter
+ constructor: (attributes) ->
+ super attributes
+ @transactions = (new Transaction(transactionAttributes) for transactionAttributes in attributes.transactions)
exports.Subscription = Subscription
View
78 lib/braintree/subscription_gateway.coffee
@@ -1,53 +1,33 @@
-Subscription = require('./subscription').Subscription
-ErrorResponse = require('./error_response').ErrorResponse
-TransactionGateway = require('./transaction_gateway').TransactionGateway
-
-SubscriptionGateway = (gateway) ->
- my = { gateway: gateway }
-
- create = (attributes, callback) ->
- my.gateway.http.post('/subscriptions', {subscription: attributes}, responseHandler(callback))
-
- cancel = (subscription_id, callback) ->
- my.gateway.http.put('/subscriptions/' + subscription_id + '/cancel', null, responseHandler(callback))
-
- find = (subscription_id, callback) ->
- my.gateway.http.get('/subscriptions/' + subscription_id, (err, response) ->
- return callback(err, null) if err
- callback(null, Subscription(response.subscription))
- )
-
- responseHandler = (callback) ->
- (err, response) ->
- return callback(err, response) if err
-
- if response.subscription
- response.success = true
- response.subscription = Subscription(response.subscription)
- callback(null, response)
- else if (response.apiErrorResponse)
- callback(null, ErrorResponse(response.apiErrorResponse))
-
- retryCharge = (subscriptionId, amount..., callback) ->
- TransactionGateway(my.gateway).sale({
+{Gateway} = require('./gateway')
+{Subscription} = require('./subscription')
+{TransactionGateway} = require('./transaction_gateway')
+
+class SubscriptionGateway extends Gateway
+ constructor: (@gateway) ->
+
+ create: (attributes, callback) ->
+ @gateway.http.post('/subscriptions', {subscription: attributes}, @responseHandler(callback))
+
+ cancel: (subscriptionId, callback) ->
+ @gateway.http.put("/subscriptions/#{subscriptionId}/cancel", null, @responseHandler(callback))
+
+ find: (subscriptionId, callback) ->
+ @gateway.http.get "/subscriptions/#{subscriptionId}", (err, response) ->
+ if err
+ callback(err, null)
+ else
+ callback(null, new Subscription(response.subscription))
+
+ responseHandler: (callback) ->
+ @createResponseHandler("subscription", Subscription, callback)
+
+ retryCharge: (subscriptionId, amount..., callback) ->
+ new TransactionGateway(@gateway).sale
amount: amount[0],
subscriptionId: subscriptionId
- }, callback)
-
- update = (subscriptionId, attributes, callback) ->
- my.gateway.http.put(
- "/subscriptions/#{subscriptionId}",
- { subscription: attributes },
- responseHandler(callback)
- )
-
- {
- cancel: cancel,
- create: create,
- find: find,
- retryCharge: retryCharge
- update: update
- }
+ , callback
-exports.SubscriptionGateway = SubscriptionGateway
+ update: (subscriptionId, attributes, callback) ->
+ @gateway.http.put("/subscriptions/#{subscriptionId}", {subscription: attributes}, @responseHandler(callback))
+exports.SubscriptionGateway = SubscriptionGateway
View
13 lib/braintree/transaction.coffee
@@ -1,10 +1,9 @@
-CreditCard = require('./credit_card').CreditCard
+{AttributeSetter} = require('./attribute_setter')
+{CreditCard} = require('./credit_card')
-Transaction = (attributes) ->
- that = {}
- for key, value of attributes
- that[key] = value
- that.creditCard = CreditCard(attributes.creditCard)
- that
+class Transaction extends AttributeSetter
+ constructor: (attributes) ->
+ super attributes
+ @creditCard = new CreditCard(attributes.creditCard)
exports.Transaction = Transaction
View
85 lib/braintree/transaction_gateway.coffee
@@ -1,58 +1,41 @@
-Transaction = require('./transaction').Transaction
-ErrorResponse = require('./error_response').ErrorResponse
+{Gateway} = require('./gateway')
+{Transaction} = require('./transaction')
+{ErrorResponse} = require('./error_response')
-TransactionGateway = (gateway) ->
- my = { gateway: gateway }
+class TransactionGateway extends Gateway
+ constructor: (@gateway) ->
- create = (attributes, callback) ->
- my.gateway.http.post('/transactions', {transaction: attributes}, responseHandler(callback))
+ create: (attributes, callback) ->
+ @gateway.http.post('/transactions', {transaction: attributes}, @responseHandler(callback))
- find = (transaction_id, callback) ->
- my.gateway.http.get('/transactions/' + transaction_id, (err, response) ->
- return callback(err, null) if err
- callback(null, Transaction(response.transaction))
+ credit: (attributes, callback) ->
+ attributes.type = 'credit'
+ @create(attributes, callback)
+
+ find: (transactionId, callback) ->
+ @gateway.http.get "/transactions/#{transactionId}", (err, response) ->
+ if err
+ callback(err, null)
+ else
+ callback(null, new Transaction(response.transaction))
+
+ refund: (transactionId, amount..., callback) ->
+ @gateway.http.post("/transactions/#{transactionId}/refund", {transaction: {amount: amount[0]}}, @responseHandler(callback))
+
+ responseHandler: (callback) ->
+ @createResponseHandler("transaction", Transaction, callback)
+
+ sale: (attributes, callback) ->
+ attributes.type = 'sale'
+ @create(attributes, callback)
+
+ submitForSettlement: (transactionId, amount..., callback) ->
+ @gateway.http.put("/transactions/#{transactionId}/submit_for_settlement",
+ {transaction: {amount: amount[0]}},
+ @responseHandler(callback)
)
- responseHandler = (callback) ->
- (err, response) ->
- return callback(err, response) if err
-
- if (response.transaction)
- response.success = true
- response.transaction = Transaction(response.transaction)
- callback(null, response)
- else if (response.apiErrorResponse)
- callback(null, ErrorResponse(response.apiErrorResponse))
-
- {
- find: find
-
- responseHandler: responseHandler
-
- credit: (attributes, callback) ->
- attributes.type = 'credit'
- create(attributes, callback)
-
- refund: (transactionId, amount..., callback) ->
- my.gateway.http.post(
- "/transactions/#{transactionId}/refund",
- { transaction: { amount: amount[0] } },
- responseHandler(callback)
- )
-
- sale: (attributes, callback) ->
- attributes.type = 'sale'
- create(attributes, callback)
-
- submitForSettlement: (transactionId, amount..., callback) ->
- my.gateway.http.put(
- "/transactions/#{transactionId}/submit_for_settlement",
- { transaction: { amount: amount[0] } },
- responseHandler(callback)
- )
-
- void: (transaction_id, callback) ->
- my.gateway.http.put('/transactions/' + transaction_id + '/void', null, responseHandler(callback))
- }
+ void: (transactionId, callback) ->
+ @gateway.http.put("/transactions/#{transactionId}/void", null, @responseHandler(callback))
exports.TransactionGateway = TransactionGateway
View
76 lib/braintree/transparent_redirect_gateway.coffee
@@ -1,85 +1,73 @@
-Digest = require('./digest').Digest
-Util = require('./util').Util
+{Digest} = require('./digest')
+{Util} = require('./util')
querystring = require('../../vendor/querystring.node.js.511d6a2/querystring')
dateFormat = require('dateformat')
-CreditCardGateway = require('./credit_card_gateway').CreditCardGateway
-CustomerGateway = require('./customer_gateway').CustomerGateway
-TransactionGateway = require('./transaction_gateway').TransactionGateway
+{CreditCardGateway} = require('./credit_card_gateway')
+{CustomerGateway} = require('./customer_gateway')
+{TransactionGateway} = require('./transaction_gateway')
exceptions = require('./exceptions')
-TransparentRedirectGateway = (gateway) ->
- KIND = {
+class TransparentRedirectGateway
+ KIND =
CREATE_CUSTOMER: 'create_customer'
UPDATE_CUSTOMER: 'update_customer'
CREATE_CREDIT_CARD: 'create_payment_method'
UPDATE_CREDIT_CARD: 'update_payment_method'
CREATE_TRANSACTION: 'create_transaction'
- }
- my = { gateway: gateway }
+ constructor: (@gateway) ->
+ @url = "#{@gateway.config.baseMerchantPath}/transparent_redirect_requests"
- generateTrData = (inputData) ->
+ generateTrData: (inputData) ->
data = Util.convertObjectKeysToUnderscores(inputData)
- data.api_version = my.gateway.config.apiVersion
+ data.api_version = @gateway.config.apiVersion
data.time = dateFormat(new Date(), 'yyyymmddHHMMss', true)
- data.public_key = my.gateway.config.publicKey
+ data.public_key = @gateway.config.publicKey
dataSegment = querystring.stringify(data)
- trDataHash = Digest.hexdigest(gateway.config.privateKey, dataSegment)
+ trDataHash = Digest.hexdigest(@gateway.config.privateKey, dataSegment)
trDataHash + "|" + dataSegment
- createCreditCardData = (data) ->
+ createCreditCardData: (data) ->
data.kind = KIND.CREATE_CREDIT_CARD
- generateTrData(data)
+ @generateTrData(data)
- updateCreditCardData = (data) ->
+ updateCreditCardData: (data) ->
data.kind = KIND.UPDATE_CREDIT_CARD
- generateTrData(data)
+ @generateTrData(data)
- createCustomerData = (data) ->
+ createCustomerData: (data) ->
data.kind = KIND.CREATE_CUSTOMER
- generateTrData(data)
+ @generateTrData(data)
- updateCustomerData = (data) ->
+ updateCustomerData: (data) ->
data.kind = KIND.UPDATE_CUSTOMER
- generateTrData(data)
+ @generateTrData(data)
- transactionData = (data) ->
+ transactionData: (data) ->
data.kind = KIND.CREATE_TRANSACTION
- generateTrData(data)
+ @generateTrData(data)
- validateQueryString = (queryString) ->
+ validateQueryString: (queryString) ->
matches = queryString.match(/^(.+)&hash=(.+?)$/)
- (Digest.hexdigest(gateway.config.privateKey, matches[1]) is matches[2])
+ (Digest.hexdigest(@gateway.config.privateKey, matches[1]) is matches[2])
- confirm = (queryString, callback) ->
+ confirm: (queryString, callback) ->
statusMatch = queryString.match(/http_status=(\d+)/)
if statusMatch && statusMatch[1]
- error = my.gateway.http.checkHttpStatus(statusMatch[1])
+ error = @gateway.http.checkHttpStatus(statusMatch[1])
return callback(error, null) if error
- if !validateQueryString(queryString)
+ if !@validateQueryString(queryString)
return callback(exceptions.InvalidTransparentRedirectHashError(), null)
params = querystring.parse(queryString)
confirmCallback = null
switch params.kind
when KIND.CREATE_CUSTOMER, KIND.UPDATE_CUSTOMER
- confirmCallback = CustomerGateway(my.gateway).responseHandler(callback)
+ confirmCallback = new CustomerGateway(@gateway).responseHandler(callback)
when KIND.CREATE_CREDIT_CARD, KIND.UPDATE_CREDIT_CARD
- confirmCallback = CreditCardGateway(my.gateway).responseHandler(callback)
+ confirmCallback = new CreditCardGateway(@gateway).responseHandler(callback)
when KIND.CREATE_TRANSACTION
- confirmCallback = TransactionGateway(my.gateway).responseHandler(callback)
- my.gateway.http.post('/transparent_redirect_requests/' + params.id + '/confirm', null, confirmCallback)
-
- url = gateway.config.baseMerchantPath + '/transparent_redirect_requests'
-
- {
- confirm: confirm
- createCreditCardData: createCreditCardData
- createCustomerData: createCustomerData
- transactionData: transactionData
- updateCreditCardData: updateCreditCardData
- updateCustomerData: updateCustomerData
- url: url
- }
+ confirmCallback = new TransactionGateway(@gateway).responseHandler(callback)
+ @gateway.http.post('/transparent_redirect_requests/' + params.id + '/confirm', null, confirmCallback)
exports.TransparentRedirectGateway = TransparentRedirectGateway
View
9 lib/braintree/util.coffee
@@ -1,5 +1,5 @@
-Util = {
- convertObjectKeysToUnderscores: (obj) ->
+class Util
+ @convertObjectKeysToUnderscores: (obj) ->
newObj = {}
for key, value of obj
newKey = Util.toUnderscore(key)
@@ -16,11 +16,10 @@ Util = {
newObj[newKey] = value
newObj
- toCamelCase: (string) ->
+ @toCamelCase: (string) ->
string.replace(/([\-\_][a-z0-9])/g, (match) -> match.toUpperCase().replace('-','').replace('_',''))
- toUnderscore: (string) ->
+ @toUnderscore: (string) ->
string.replace(/([A-Z])/g, (match) -> "_" + match.toLowerCase())
-}
exports.Util = Util
View
11 lib/braintree/validation_error.coffee
@@ -1,8 +1,7 @@
-ValidationError = (error) ->
- {
- attribute: error.attribute,
- code: error.code,
- message: error.message
- }
+class ValidationError
+ constructor: (error) ->
+ @attribute = error.attribute
+ @code = error.code
+ @message = error.message
exports.ValidationError = ValidationError
View
56 lib/braintree/validation_errors_collection.coffee
@@ -1,39 +1,41 @@
-Util = require('./util').Util
-ValidationError = require('./validation_error').ValidationError
+{Util} = require('./util')
+{ValidationError} = require('./validation_error')
-ValidationErrorsCollection = (errorAttributes) ->
- my = {
- validationErrors: {},
- errorCollections: {}
- }
+class ValidationErrorsCollection
+ constructor: (errorAttributes) ->
+ @validationErrors = {}
+ @errorCollections = {}
- buildErrors = (errors) ->
+ for key, val of errorAttributes
+ if key is 'errors'
+ @buildErrors(val)
+ else
+ @errorCollections[key] = new ValidationErrorsCollection(val)
+
+ buildErrors: (errors) ->
for item in errors
key = Util.toCamelCase(item.attribute)
- my.validationErrors[key] or= []
- my.validationErrors[key].push ValidationError(item)
+ @validationErrors[key] or= []
+ @validationErrors[key].push(new ValidationError(item))
+
+ deepErrors: ->
+ errors = []
- for key, val of errorAttributes
- if key is 'errors'
- buildErrors(val)
- else
- my.errorCollections[key] = ValidationErrorsCollection(val)
+ for key, val of @validationErrors
+ errors = errors.concat(val)
+ for key, val of @errorCollections
+ errors = errors.concat(val.deepErrors())
- {
- deepErrors: () ->
- deepErrors = []
- for key, val of my.validationErrors
- deepErrors = deepErrors.concat(val)
+ errors
- for key, val of my.errorCollections
- deepErrors = deepErrors.concat(val.deepErrors())
+ for: (name) ->
+ @errorCollections[name]
- deepErrors
+ forIndex: (index) ->
+ @errorCollections["index#{index}"]
- for: (name) -> my.errorCollections[name]
- forIndex: (index) -> my.errorCollections["index#{index}"]
- on: (name) -> my.validationErrors[name]
- }
+ on: (name) ->
+ @validationErrors[name]
exports.ValidationErrorsCollection = ValidationErrorsCollection
View
26 lib/braintree/xml_parser.coffee
@@ -1,11 +1,14 @@
sys = require('sys')
xml = require('o3-xml')
-Util = require('./util').Util
+{Util} = require('./util')
-XmlParser = ->
+class XmlParser
TEXT_NODE = 3
- convertNodeToObject = (node) ->
+ @parse: (text) ->
+ new XmlParser().parse(text)
+
+ convertNodeToObject: (node) ->
object = {}
obj = {}
for child in node.childNodes
@@ -21,21 +24,14 @@ XmlParser = ->
else if child.childNodes.length is 0 && child.attributes.length is 1 && child.attributes[0].name is 'type' && child.attributes[0].value is 'array'
obj[name] = []
else if child.attributes.length is 1 && child.attributes[0].name is 'type' && child.attributes[0].value is 'array'
- obj[name] = (convertNodeToObject(arrayItem)[Util.toCamelCase(arrayItem.nodeName)] for arrayItem in child.childNodes when arrayItem.nodeType isnt TEXT_NODE)
+ obj[name] = (@convertNodeToObject(arrayItem)[Util.toCamelCase(arrayItem.nodeName)] for arrayItem in child.childNodes when arrayItem.nodeType isnt TEXT_NODE)
else
- obj[name] = convertNodeToObject(child)[Util.toCamelCase(child.nodeName)]
+ obj[name] = @convertNodeToObject(child)[Util.toCamelCase(child.nodeName)]
object[Util.toCamelCase(node.nodeName)] = obj
object
- parse = (body) ->
+ parse: (body) ->
doc = xml.parseFromString(body)
- convertNodeToObject(doc.documentElement)
-
- {
- parse: parse
- }
-
+ @convertNodeToObject(doc.documentElement)
-exports.XmlParser = {
- parse: (text) -> XmlParser().parse(text)
-}
+exports.XmlParser = XmlParser
View
1  node_modules/.bin/cake
View
1  node_modules/.bin/coffee
View
1  node_modules/.bin/vows
View
4 package.json
@@ -1,11 +1,11 @@
{
"name" : "braintree",
- "version" : "0.2.0",
+ "version" : "0.3.0",
"description" : "A library for integrating with Braintree.",
"keywords" : ["payments"],
"homepage" : "http://github.com/braintree/braintree_node",
"author" : "Braintree <code@braintreepayments.com> (http://www.braintreepayments.com)",
- "main" : "./lib/braintree",
+ "main" : "./lib/braintree.js",
"repository" : { "type": "git", "url" : "https://github.com/braintree/braintree_node.git" },
"dependencies" : {},
"engines" : { "node": "~0.4.7" },
View
4 spec/braintree/braintree_spec.js
@@ -5,8 +5,8 @@ var braintree = specHelper.braintree;
vows.describe('Braintree').addBatch({
'version': {
topic: braintree.version,
- 'is 0.2.0': function (version) {
- assert.equal(version, '0.2.0');
+ 'is 0.3.0': function (version) {
+ assert.equal(version, '0.3.0');
}
},
View
8 spec/braintree/http_spec.js
@@ -8,7 +8,7 @@ vows.describe('Http').addBatch({
'request': {
'when the http response status is 500': {
topic: function () {
- var http = Http(Config(specHelper.defaultConfig));
+ var http = new Http(new Config(specHelper.defaultConfig));
http.post('/test/error', '', this.callback);
},
'returns a ServerError': function (err, response) {
@@ -18,7 +18,7 @@ vows.describe('Http').addBatch({
'when the http response status is 503': {
topic: function () {
- var http = Http(Config(specHelper.defaultConfig));
+ var http = new Http(new Config(specHelper.defaultConfig));
http.post('/test/maintenance', '', this.callback);
},
'returns a down for maintenance error': function (err, response) {
@@ -28,7 +28,7 @@ vows.describe('Http').addBatch({
'can hit the sandbox': {
topic: function () {
- var http = Http(Config({
+ var http = new Http(new Config({
environment: braintree.Environment.Sandbox,
merchantId: 'node',
publicKey: 'node',
@@ -44,7 +44,7 @@ vows.describe('Http').addBatch({
'can hit production': {
topic: function () {
- var http = Http(Config({
+ var http = new Http(new Config({
environment: braintree.Environment.Production,
merchantId: 'node',
publicKey: 'node',
View
111 spec/braintree/settlement_batch_summary_gateway_spec.js
@@ -0,0 +1,111 @@
+require('../spec_helper');
+
+var _ = require('underscore')._,
+ braintree = specHelper.braintree;
+
+vows.describe('SettlementBatchSummaryGateway').addBatch({
+ 'generate': {
+ 'when there is no data': {
+ topic: function () {
+ specHelper.defaultGateway.settlementBatchSummary.generate(
+ {settlementDate: "2011-01-01"},
+ this.callback
+ );
+ },
+
+ 'is successful': function (err, response) {
+ assert.isTrue(response.success);
+ },
+
+ 'returns an empty array': function (err, response) {
+ assert.deepEqual(response.settlementBatchSummary.records, []);
+ }
+ },
+
+ 'if date can not be parsed': {
+ topic: function () {
+ specHelper.defaultGateway.settlementBatchSummary.generate(
+ {settlementDate: "NOT A DATE"},
+ this.callback
+ );
+ },
+
+ 'is not successful': function (err, response) {
+ assert.isFalse(response.success);
+ },
+
+ 'has errors on the date': function (err, response) {
+ assert.equal(response.errors.for('settlementBatchSummary').on('settlementDate')[0].code, '82302');
+ assert.equal(response.errors.for('settlementBatchSummary').on('settlementDate')[0].attribute, 'settlement_date');
+ }
+ },
+
+ 'if given a valid settlement date': {
+ topic: function () {
+ var callback = this.callback;
+ specHelper.defaultGateway.transaction.credit({
+ amount: '5.00',
+ creditCard: {
+ number: '4111111111111111',
+ expirationDate: '05/12'
+ }
+ }, function (err, response) {
+ specHelper.settleTransaction(response.transaction.id, function (err, response) {
+ formattedDate = specHelper.dateToMdy(new Date());
+ specHelper.defaultGateway.settlementBatchSummary.generate(
+ {settlementDate: formattedDate},
+ callback
+ );
+ });
+ })
+ },
+
+ 'is successful': function (err, response) {
+ assert.isTrue(response.success);
+ },
+
+ 'returns transactions on a given day': function (err, response) {
+ var records = response.settlementBatchSummary.records
+ var visaRecords = _.select(records, function (record) {
+ return record['cardType'] === 'Visa';
+ });
+
+ assert.ok(visaRecords[0]['count'] >= 1);
+ assert.ok(parseFloat(visaRecords[0]['amountSettled']) >= parseFloat("5.00"));
+ }
+ },
+
+ 'if given a custom field to group by': {
+ topic: function () {
+ var callback = this.callback;
+ specHelper.defaultGateway.transaction.credit({
+ amount: '5.00',
+ creditCard: {
+ number: '4111111111111111',
+ expirationDate: '05/12'
+ },
+ customFields: {
+ store_me: 1
+ }
+ }, function (err, response) {
+ specHelper.settleTransaction(response.transaction.id, function (err, response) {
+ formattedDate = specHelper.dateToMdy(new Date);
+ specHelper.defaultGateway.settlementBatchSummary.generate(
+ {settlementDate: formattedDate, groupByCustomField: "store_me"},
+ callback
+ );
+ });
+ })
+ },
+
+ 'is successful': function (err, response) {
+ assert.isTrue(response.success);
+ },
+
+ 'groups by the custom field': function (err, response) {
+ var records = response.settlementBatchSummary.records
+ assert.ok(records[0]['store_me']);
+ }
+ }
+ }
+}).export(module);
View
2  spec/braintree/subscription_gateway_spec.js
@@ -133,7 +133,7 @@ vows.describe('SubscriptionGateway').addBatch({
'has the expected first billing date': function (err, response) {
var expectedDate = new Date();
expectedDate.setFullYear(expectedDate.getFullYear() + 1);
- var expectedDateString = dateFormat(expectedDate, 'yyyy-mm-dd');
+ var expectedDateString = dateFormat(expectedDate, 'yyyy-mm-dd', true);
assert.equal(response.subscription.firstBillingDate, expectedDateString);
},
View
14 spec/braintree/transaction_gateway_spec.js
@@ -15,15 +15,11 @@ var createTransactionToRefund = function (callback) {
options: { submitForSettlement: true }
},
function (err, result) {
- specHelper.defaultGateway._gateway.http.put(
- '/transactions/' + result.transaction.id + '/settle',
- null,
- function (err, settleResult) {
- specHelper.defaultGateway.transaction.find(result.transaction.id, function (err, transaction) {
- callback(transaction);
- });
- }
- );
+ specHelper.settleTransaction(result.transaction.id, function (err, settleResult) {
+ specHelper.defaultGateway.transaction.find(result.transaction.id, function (err, transaction) {
+ callback(transaction);
+ });
+ });
}
)
};
View
2  spec/braintree/validation_errors_collection_spec.js
@@ -4,7 +4,7 @@ var ValidationErrorsCollection = require('../../lib/braintree/validation_errors_
vows.describe('ValidationErrorsCollection').addBatch({
'on': {
'with multiple errors on a single attribute': {
- topic: ValidationErrorsCollection({
+ topic: new ValidationErrorsCollection({
errors: [
{attribute: 'foo', code: '1'},
{attribute: 'foo', code: '2'},
View
32 spec/spec_helper.coffee
@@ -1,5 +1,5 @@
http = require('http')
-Util = require('../lib/braintree/util').Util
+{Util} = require('../lib/braintree/util')
querystring = require('../vendor/querystring.node.js.511d6a2/querystring')
sys = require('sys')
@@ -13,7 +13,7 @@ GLOBAL.assert.isEmptyArray = (array) ->
GLOBAL.inspect = (object) ->
sys.puts(sys.inspect(object))
-braintree = require('./../lib/braintree')
+braintree = require('./../lib/braintree.js')
defaultConfig = {
environment: braintree.Environment.Development
@@ -41,17 +41,24 @@ addOns = {
}
makePastDue = (subscription, callback) ->
- defaultGateway._gateway.http.put(
+ defaultGateway.http.put(
"/subscriptions/#{subscription.id}/make_past_due?days_past_due=1",
null,
callback
)
+settleTransaction = (transactionId, callback) ->
+ defaultGateway.http.put(
+ "/transactions/#{transactionId}/settle",
+ null,
+ callback
+ )
+
simulateTrFormPost = (url, trData, inputFormData, callback) ->
client = http.createClient(
- specHelper.defaultGateway._gateway.config.environment.port,
- specHelper.defaultGateway._gateway.config.environment.server,
- specHelper.defaultGateway._gateway.config.environment.ssl
+ specHelper.defaultGateway.config.environment.port,
+ specHelper.defaultGateway.config.environment.server,
+ specHelper.defaultGateway.config.environment.ssl
)
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
@@ -68,13 +75,26 @@ simulateTrFormPost = (url, trData, inputFormData, callback) ->
callback(null, response.headers.location.split('?', 2)[1])
)
+dateToMdy = (date) ->
+ year = date.getFullYear().toString()
+ month = (date.getMonth() + 1).toString()
+ day = date.getDate().toString()
+ if month.length == 1
+ month = "0" + month
+ if day.length == 1
+ day = "0" + day
+ formattedDate = year + '-' + month + '-' + day
+ return formattedDate
+
GLOBAL.specHelper = {
addOns: addOns
braintree: braintree
+ dateToMdy: dateToMdy
defaultConfig: defaultConfig
defaultGateway: defaultGateway
makePastDue: makePastDue
multiplyString: multiplyString
plans: plans
+ settleTransaction: settleTransaction
simulateTrFormPost: simulateTrFormPost
}
Please sign in to comment.
Something went wrong with that request. Please try again.