@@ -1,229 +1,81 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE OverloadedStrings #-}
3−{-# LANGUAGE UndecidableInstances #-}
4−module Web.Connexpay.Payments ( CreditCard(..)
5− , AuthResponse(..)
6− , authorisePayment
7− , VoidRequest(..)
8− , voidPayment
9− , CaptureResponse(..)
10− , capturePayment
11− , cancelPayment
12− , returnPayment
13− ) where
1+module Web.Connexpay.Payments
2+ ( AuthRequest(..)
3+ , USD(..)
4+ , CreditCard(..)
5+ , ExpirationDate(..)
6+ , Customer(..)
7+ , RiskData(..)
8+ , AuthorizeResult(..)
9+ , AuthResponse(..)
10+ , TransactionStatus(..)
11+ , authorisePayment
12+ , VoidRequest(..)
13+ , voidPayment
14+ , CaptureResponse(..)
15+ , Sale(..)
16+ , capturePayment
17+ , cancelPayment
18+ , returnPayment
19+ ) where
1420
15−import Control.Exception (throwIO)
16−import Control.Monad (when)
17−import Control.Monad.Except (throwError)
18−import Control.Monad.Reader (asks)
19−import Control.Monad.Writer.Strict
2021import Data.Aeson
21−import Data.Aeson.KeyMap qualified as KeyMap
22−import Data.Aeson.Types (Pair, typeMismatch)
23−import Data.ByteString.Lazy qualified as ByteString
24−import Data.Int (Int32)
25−import Data.Money
26−import Data.Proxy
27−import Data.Text (Text)
28−import Data.Text qualified as Text
29−import Data.Text.Encoding qualified as Text
30−import GHC.TypeError as TypeError
31−import Network.HTTP.Req
3222
33−import Web.Connexpay.Data
23+import Web.Connexpay.Http
24+import Web.Connexpay.Payments.Types
3425import Web.Connexpay.Types
35−import Web.Connexpay.Utils
3626
37−-- | Credit card info
38−-- No 'Show' instance should be made for this type
39−-- in order to avoid sensitive data leaks.
40−data CreditCard = CreditCard { number :: Text -- ^ Credit card number, as 'Text'.
41− , cardholder :: Maybe Text -- ^ Cardholder name, optional.
42− , expiration :: (Word, Word) -- ^ Expiration date (month,year).
43− , cvv :: Maybe Text -- ^ CVC/CVV code.
44− }
45−
46−type ShowError = TypeError.Text "CreditCard must not be shown in order to avoid leaking sensitive data"
47−
48−instance TypeError ShowError => Show CreditCard where
49− show = error "UNREACHABLE"
50−
51−instance ToJSON CreditCard where
52− toJSON cc = object
53− $ execWriter
54− $ do tell ["CardNumber" .= cc.number]
55− whenJust cc.cardholder $ \name ->
56− tell ["CardHolderName" .= name]
57− whenJust cc.cvv $ \cvv ->
58− tell ["Cvv2" .= cvv]
59− let expDate = padDate (tshow (snd cc.expiration)) <> padDate (tshow (fst cc.expiration))
60− tell ["ExpirationDate" .= expDate]
61−
62−padDate :: Text -> Text
63−padDate t | Text.length t == 1 = "0" <> t
64− | otherwise = t
65−
66−sendRequest' :: HttpResponse resp
67− => Proxy resp -> Text -> (forall scheme. Option scheme) -> [Pair]
68− -> ConnexpayM resp
69−sendRequest' resp endpoint opts body =
70− do mtok <- bearerToken
71− tok <- case mtok of
72− Just t -> pure t
73− Nothing -> throwError (ConnectionError $ TokenError "No authentication token available. Check connection parameters?")
74− host <- asks (.url)
75− tls <- asks (.useTLS)
76− let auth = header "Authorization" ("Bearer " <> Text.encodeUtf8 tok)
77− headers = auth <> opts
78− url s = s host /: "api" /: "v1" /: endpoint
79− obj <- object <$> addGuid body
80− let jbody = ReqBodyJson obj
81− r <- if tls
82− then reqCb POST (url https) jbody resp headers (logRequest obj)
83− else reqCb POST (url http) jbody resp headers (logRequest obj)
84− pure r
85− where
86− addGuid b =
87− do guid <- asks (.deviceGuid)
88− return (b <> [ "DeviceGuid" .= show guid ])
89− logRequest v r =
90− do log_ <- asks (.logAction)
91− -- Remove card info from logs
92− let v' = case v of
93− Object obj
94− | Just c <- KeyMap.lookup "Card" obj -> Object (KeyMap.insert "Card" (replaceCard c) obj)
95− other -> other
96− msg = Text.unlines [ "Connexpay request:"
97− , tshow r
98− , Text.decodeUtf8 (ByteString.toStrict $ encode v')
99− ]
100− _ <- liftIO (log_ msg)
101− return r
102− replaceCard (Object c) =
103− Object
104− $ KeyMap.insert "CardNumber" (String "<REDACTED>")
105− $ KeyMap.insert "Cvv2" (String "<REDACTED>")
106− $ c
107− replaceCard v = v
108−
109−sendRequestJson :: FromJSON a => Text -> [Pair] -> ConnexpayM a
110−sendRequestJson endpoint body = do
111− r <- sendRequest' lbsResponse endpoint accept body
112− let b = responseBody r
113− logResponseBody r b
114− case eitherDecode b of
115− Right x -> return x
116− Left e -> liftIO (throwIO (JsonHttpException e))
117− where
118− accept = header "Accept" "application/json"
119−
120−sendRequest_ :: Text -> [Pair] -> ConnexpayM ()
121−sendRequest_ ep body = do
122− r <- sendRequest' lbsResponse ep mempty body
123− let b = responseBody r
124− logResponseBody r b
125−
126−data AuthResponse = AuthResponse { paymentGuid :: AuthOnlyGuid
127− , status :: TransactionStatus
128− , processorStatusCode :: Maybe Text
129− , processorMessage :: Maybe Text
130− , addressVerificationCode :: Maybe Text
131− , cvvVerificationCode :: Maybe Text
132− } deriving (Show)
133−
134−instance FromJSON AuthResponse where
135− parseJSON (Object o) = AuthResponse <$> o .: "guid"
136− <*> o .: "status"
137− <*> o .:? "processorStatusCode"
138− <*> o .:? "processorResponseMessage"
139− <*> o .:? "addressVerificationCode"
140− <*> o .:? "cvvVerificationCode"
141− parseJSON v = typeMismatch "AuthReponse" v
14227
14328-- | Authorise a credit card payment.
144−authorisePayment :: CreditCard -- ^ Credit card details (see 'CreditCard')
145− -> Money USD -- ^ Amount to charge, USD
146− -> Maybe Text -- ^ Invoice description
147− -> Maybe Text -- ^ Merchant description that will appear in a customer's statement.
148− -> ConnexpayM AuthResponse
149−authorisePayment cc amt invoice vendor =
150− do rbody <- sendRequestJson "authonlys" body
151− -- Special case for Connexpay local transaction
152− -- This status means that the transaction was registered,
153− -- but Connexpay stopped its processing and it won't be
154− -- moved any further.
155− -- Also, when I asked Ken from Connexpay about this,
156− -- he told me he had never seen this status before.
157− when (rbody.status == TransactionCreatedLocal) $
158− throwError (PaymentFailure LocalTransaction)
159− pure rbody
160− where body = execWriter $
161− do tell [ "Card" .= cc ]
162− tell [ "Amount" .= getAmount amt ]
163− whenJust invoice $ \i ->
164− tell [ "OrderNumber" .= i ]
165− whenJust vendor $ \v ->
166− tell [ "StatementDescription" .= v ]
167− -- We are supposed to pass RiskData, but it still
168− -- can be an empty object. Consider population this
169− -- should the need arise.
170− tell [ "RiskData" .= KeyMap.empty @() ]
171−
172−data VoidRequest = VoidAuthorized AuthOnlyGuid
173− | VoidCaptured SaleGuid (Maybe (Money USD))
29+authorisePayment
30+ :: Connexpay -> Env -> AuthRequest -> IO (Response AuthError AuthorizeResult)
31+authorisePayment connexpay env raw =
32+ bimapResponse (guessErrorType guessAuthError) postProcessAuthResponse <$>
33+ doRequest connexpay env "authonlys" RequestBody
34+ { raw
35+ , logMasker = maskAuthRequest
36+ }
17437
17538-- | Void payment
176−voidPayment :: VoidRequest
177− -> ConnexpayM ()
178−voidPayment (VoidAuthorized pid) = sendRequest_ "void" body
179− where body = [ "AuthOnlyGuid" .= show pid ]
180−voidPayment (VoidCaptured pid amt) = sendRequest_ "void" body
181− where body = execWriter $
182− do tell [ "SaleGuid" .= show pid ]
183− whenJust amt $ \m ->
184− tell [ "Amount" .= getAmount m ]
185−
186−-- | Internal data type for Capture requests.
187−data CPTransaction = CPTransaction { expectedPayments :: Int32 }
188−
189−instance ToJSON CPTransaction where
190− toJSON t = object [ "ExpectedPayments" .= t.expectedPayments ]
191−
192−-- | Response for the payment capture request
193−data CaptureResponse = CaptureResponse { captureGuid :: CaptureGuid
194− , saleGuid :: SaleGuid
195− , saleStatus :: TransactionStatus
196− } deriving (Show)
197−
198−instance FromJSON CaptureResponse where
199− parseJSON (Object o) =
200− do cguid <- o .: "guid"
201− sale <- o .: "sale"
202− saleGuid <- sale .: "guid"
203− status <- sale .: "status"
204− pure (CaptureResponse cguid saleGuid status)
205− parseJSON v = typeMismatch "CaptureResponse" v
39+voidPayment :: Connexpay -> Env -> VoidRequest -> IO (Response () ())
40+voidPayment connexpay env raw = doRequest_ connexpay env "void" RequestBody
41+ { raw
42+ , logMasker = id
43+ }
20644
20745-- | Capture payment, previously authorised through 'authorisePayment'.
208−capturePayment :: SaleGuid -- ^ Sales GUID, obtained from 'authorisePayment'.
209− -> ConnexpayM CaptureResponse
210−capturePayment pid = sendRequestJson "Captures" body
211− where body = [ "AuthOnlyGuid" .= show pid
212− , "ConnexPayTransaction" .= CPTransaction 1 ]
46+capturePayment :: Connexpay
47+ -> Env
48+ -> AuthOnlyGuid -- ^ Sales GUID, obtained from 'authorisePayment'.
49+ -> IO (Response () CaptureResponse)
50+capturePayment connexpay env pid = doRequest connexpay env "Captures" RequestBody
51+ { raw = object
52+ [ "AuthOnlyGuid" .= pid
53+ , "ConnexPayTransaction" .= CPTransaction 1
54+ ]
55+ , logMasker = id
56+ }
21357
21458-- | Cancel voided or captured payment.
21559-- In case of an authorised-only payment, voiding is performed.
21660-- Otherwise, a payment goes through a refund process.
217−cancelPayment :: SaleGuid -- ^ Sales GUID, obtained from 'capturePayment'.
218− -> ConnexpayM ()
219−cancelPayment pid = sendRequest_ "cancel" body
220− where body = [ "SaleGuid" .= show pid ]
221−
222−returnPayment :: SaleGuid -- ^ Sales GUID, obtained from 'capturePayment'.
223− -> Maybe (Money USD)
224− -> ConnexpayM ()
225−returnPayment pid amt = sendRequest_ "returns" body
226− where body = execWriter $
227− do tell [ "SaleGuid" .= show pid ]
228− whenJust amt $ \m ->
229− tell [ "Amount" .= getAmount m ]
61+cancelPayment :: Connexpay
62+ -> Env
63+ -> SaleGuid -- ^ Sales GUID, obtained from 'capturePayment'.
64+ -> IO (Response () ())
65+cancelPayment connexpay env pid = doRequest_ connexpay env "cancel" RequestBody
66+ { raw = object [ "SaleGuid" .= pid ]
67+ , logMasker = id
68+ }
69+
70+returnPayment :: Connexpay
71+ -> Env
72+ -> SaleGuid -- ^ Sales GUID, obtained from 'capturePayment'.
73+ -> USD
74+ -> IO (Response () ())
75+returnPayment connexpay env pid amt = doRequest_ connexpay env "returns" RequestBody
76+ { raw = object
77+ [ "SaleGuid" .= pid
78+ , "Amount" .= amt
79+ ]
80+ , logMasker = id
81+ }