Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
feat(connector): [Boku] Implement Authorize, Psync, Refund and Rsync flow (#1699)
Sakil Mostak9cba7da0d3d4
diff --git a/Cargo.lock b/Cargo.lockindex 66825779f0..fdea4e03b7 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4000,6 +4000,7 @@ dependencies = ["ring","router_derive","router_env",+ "roxmltree","serde","serde_json","serde_path_to_error",@@ -4064,6 +4065,15 @@ dependencies = ["vergen",]+[[package]]+name = "roxmltree"+version = "0.18.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8f595a457b6b8c6cda66a48503e92ee8d19342f905948f29c383200ec9eb1d8"+dependencies = [+ "xmlparser",+]+[[package]]name = "rust-embed"version = "6.7.0"diff --git a/config/config.example.toml b/config/config.example.tomlindex 0415330c89..664477ec91 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -157,7 +157,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"bambora.base_url = "https://api.na.bambora.com"bitpay.base_url = "https://test.bitpay.com"bluesnap.base_url = "https://sandbox.bluesnap.com/"-boku.base_url = "https://country-api4-stage.boku.com"+boku.base_url = "https://$-api4-stage.boku.com"braintree.base_url = "https://api.sandbox.braintreegateway.com/"cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"checkout.base_url = "https://api.sandbox.checkout.com/"diff --git a/config/development.toml b/config/development.tomlindex c5b85d4a1f..eec0044596 100644--- a/config/development.toml+++ b/config/development.toml@@ -123,7 +123,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"bambora.base_url = "https://api.na.bambora.com"bitpay.base_url = "https://test.bitpay.com"bluesnap.base_url = "https://sandbox.bluesnap.com/"-boku.base_url = "https://country-api4-stage.boku.com"+boku.base_url = "https://$-api4-stage.boku.com"braintree.base_url = "https://api.sandbox.braintreegateway.com/"cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"checkout.base_url = "https://api.sandbox.checkout.com/"diff --git a/config/docker_compose.toml b/config/docker_compose.tomlindex a8a8ecde60..cc93127fb6 100644--- a/config/docker_compose.toml+++ b/config/docker_compose.toml@@ -80,7 +80,7 @@ authorizedotnet.base_url = "https://apitest.authorize.net/xml/v1/request.api"bambora.base_url = "https://api.na.bambora.com"bitpay.base_url = "https://test.bitpay.com"bluesnap.base_url = "https://sandbox.bluesnap.com/"-boku.base_url = "https://country-api4-stage.boku.com"+boku.base_url = "https://$-api4-stage.boku.com"braintree.base_url = "https://api.sandbox.braintreegateway.com/"cashtocode.base_url = "https://cluster05.api-test.cashtocode.com"checkout.base_url = "https://api.sandbox.checkout.com/"diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rsindex 129472c9d0..53303a2230 100644--- a/crates/api_models/src/enums.rs+++ b/crates/api_models/src/enums.rs@@ -78,7 +78,7 @@ pub enum Connector {Bitpay,Bambora,Bluesnap,- // Boku, added as template code for future usage+ Boku,Braintree,Cashtocode,Checkout,@@ -192,7 +192,7 @@ pub enum RoutableConnectors {Bitpay,Bambora,Bluesnap,- // Boku, added as template code for future usage+ Boku,Braintree,Cashtocode,Checkout,diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rsindex eac24ac075..e562c5914f 100644--- a/crates/common_utils/src/ext_traits.rs+++ b/crates/common_utils/src/ext_traits.rs@@ -61,6 +61,15 @@ wherewhereSelf: Serialize;+ ///+ /// Functionality, for specifically encoding `Self` into `String`+ /// after serialization by using `serde::Serialize`+ /// specifically, to convert into XML `String`.+ ///+ fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError>+ where+ Self: Serialize;+////// Functionality, for specifically encoding `Self` into `serde_json::Value`/// after serialization by using `serde::Serialize`@@ -131,6 +140,16 @@ where.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))}+ fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError>+ where+ Self: Serialize,+ {+ quick_xml::se::to_string(self)+ .into_report()+ .change_context(errors::ParsingError::EncodeError("xml"))+ .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))+ }+fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError>whereSelf: Serialize,diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 45091f0f61..dc2ad5370e 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -69,6 +69,7 @@ rand = "0.8.5"regex = "1.8.4"reqwest = { version = "0.11.18", features = ["json", "native-tls", "gzip", "multipart"] }ring = "0.16.20"+roxmltree = "0.18.0"serde = { version = "1.0.163", features = ["derive"] }serde_json = "1.0.96"serde_path_to_error = "0.1.11"diff --git a/crates/router/src/connector/boku.rs b/crates/router/src/connector/boku.rsindex 70aa46e99b..628417f487 100644--- a/crates/router/src/connector/boku.rs+++ b/crates/router/src/connector/boku.rs@@ -2,14 +2,20 @@ mod transformers;use std::fmt::Debug;-use error_stack::{IntoReport, ResultExt};-use masking::ExposeInterface;+use common_utils::ext_traits::XmlExt;+use error_stack::{IntoReport, Report, ResultExt};+use masking::{ExposeInterface, PeekInterface, Secret, WithType};+use ring::hmac;+use roxmltree;+use time::OffsetDateTime;use transformers as boku;use crate::{configs::settings,+ consts,core::errors::{self, CustomResult},- headers,+ headers, logger,+ routes::metrics,services::{self,request::{self, Mask},@@ -20,7 +26,7 @@ use crate::{api::{self, ConnectorCommon, ConnectorCommonExt},ErrorResponse, Response,},- utils::{self, BytesExt},+ utils::{self, BytesExt, OptionExt},};#[derive(Debug, Clone)]@@ -56,16 +62,40 @@ wherefn build_headers(&self,req: &types::RouterData<Flow, Request, Response>,- _connectors: &settings::Connectors,+ connectors: &settings::Connectors,) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {- let mut header = vec![(- headers::CONTENT_TYPE.to_string(),- types::PaymentsAuthorizeType::get_content_type(self)- .to_string()- .into(),- )];- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;- header.append(&mut api_key);+ let connector_auth = boku::BokuAuthType::try_from(&req.connector_auth_type)?;++ let boku_url = Self::get_url(self, req, connectors)?;++ let content_type = Self::common_get_content_type(self);++ let connector_method = Self::get_http_method(self);++ let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;++ let secret_key = boku::BokuAuthType::try_from(&req.connector_auth_type)?+ .key_id+ .expose();++ let to_sign = format!(+ "{} {}\nContent-Type: {}\n{}",+ connector_method, boku_url, &content_type, timestamp+ );++ let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());++ let tag = hmac::sign(&key, to_sign.as_bytes());++ let signature = hex::encode(tag);++ let auth_val = format!("2/HMAC_SHA256(H+SHA256(E)) timestamp={timestamp}, signature={signature} signed-headers=Content-Type, key-id={}", connector_auth.key_id.peek());++ let header = vec![+ (headers::CONTENT_TYPE.to_string(), content_type.into()),+ (headers::AUTHORIZATION.to_string(), auth_val.into_masked()),+ ];+Ok(header)}}@@ -76,12 +106,12 @@ impl ConnectorCommon for Boku {}fn common_get_content_type(&self) -> &'static str {- "application/json"+ "text/xml;charset=utf-8"}fn validate_auth_type(&self,val: &types::ConnectorAuthType,- ) -> Result<(), error_stack::Report<errors::ConnectorError>> {+ ) -> Result<(), Report<errors::ConnectorError>> {boku::BokuAuthType::try_from(val)?;Ok(())}@@ -90,33 +120,24 @@ impl ConnectorCommon for Boku {connectors.boku.base_url.as_ref()}- fn get_auth_header(- &self,- auth_type: &types::ConnectorAuthType,- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {- let auth = boku::BokuAuthType::try_from(auth_type)- .change_context(errors::ConnectorError::FailedToObtainAuthType)?;- Ok(vec![(- headers::AUTHORIZATION.to_string(),- auth.api_key.expose().into_masked(),- )])- }-fn build_error_response(&self,res: Response,) -> CustomResult<ErrorResponse, errors::ConnectorError> {- let response: boku::BokuErrorResponse = res+ let response_data: Result<boku::BokuErrorResponse, Report<errors::ConnectorError>> = res.response- .parse_struct("BokuErrorResponse")- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;-- Ok(ErrorResponse {- status_code: res.status_code,- code: response.code,- message: response.message,- reason: response.reason,- })+ .parse_struct("boku::BokuErrorResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed);++ match response_data {+ Ok(response) => Ok(ErrorResponse {+ status_code: res.status_code,+ code: response.code,+ message: response.message,+ reason: response.reason,+ }),+ Err(_) => get_xml_deserialized(res),+ }}}@@ -147,16 +168,25 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::Pself.build_headers(req, connectors)}+ fn get_http_method(&self) -> services::Method {+ services::Method::Post+ }+fn get_content_type(&self) -> &'static str {self.common_get_content_type()}fn get_url(&self,- _req: &types::PaymentsAuthorizeRouterData,- _connectors: &settings::Connectors,+ req: &types::PaymentsAuthorizeRouterData,+ connectors: &settings::Connectors,) -> CustomResult<String, errors::ConnectorError> {- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())+ let boku_url = get_country_url(+ req.connector_meta_data.clone(),+ self.base_url(connectors).to_string(),+ )?;++ Ok(format!("{boku_url}/billing/3.0/begin-single-charge"))}fn get_request_body(@@ -166,7 +196,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::Plet req_obj = boku::BokuPaymentsRequest::try_from(req)?;let boku_req = types::RequestBody::log_and_get_request_body(&req_obj,- utils::Encode::<boku::BokuPaymentsRequest>::encode_to_string_of_json,+ utils::Encode::<boku::BokuPaymentsRequest>::encode_to_string_of_xml,).change_context(errors::ConnectorError::RequestEncodingFailed)?;Ok(Some(boku_req))@@ -197,10 +227,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::Pdata: &types::PaymentsAuthorizeRouterData,res: Response,) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {- let response: boku::BokuPaymentsResponse = res- .response- .parse_struct("Boku PaymentsAuthorizeResponse")+ let response_data = String::from_utf8(res.response.to_vec())+ .into_report()+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;++ let response = response_data+ .parse_xml::<boku::BokuResponse>()+ .into_report().change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+types::RouterData::try_from(types::ResponseRouterData {response,data: data.clone(),@@ -233,10 +268,28 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRefn get_url(&self,- _req: &types::PaymentsSyncRouterData,- _connectors: &settings::Connectors,+ req: &types::PaymentsSyncRouterData,+ connectors: &settings::Connectors,) -> CustomResult<String, errors::ConnectorError> {- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())+ let boku_url = get_country_url(+ req.connector_meta_data.clone(),+ self.base_url(connectors).to_string(),+ )?;++ Ok(format!("{boku_url}/billing/3.0/query-charge"))+ }++ fn get_request_body(+ &self,+ req: &types::PaymentsSyncRouterData,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let req_obj = boku::BokuPsyncRequest::try_from(req)?;+ let boku_req = types::RequestBody::log_and_get_request_body(+ &req_obj,+ utils::Encode::<boku::BokuPsyncRequest>::encode_to_string_of_xml,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(boku_req))}fn build_request(@@ -250,6 +303,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe.url(&types::PaymentsSyncType::get_url(self, req, connectors)?).attach_default_headers().headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)+ .body(types::PaymentsSyncType::get_request_body(self, req)?).build(),))}@@ -259,10 +313,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRedata: &types::PaymentsSyncRouterData,res: Response,) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {- let response: boku::BokuPaymentsResponse = res- .response- .parse_struct("boku PaymentsSyncResponse")+ let response_data = String::from_utf8(res.response.to_vec())+ .into_report().change_context(errors::ConnectorError::ResponseDeserializationFailed)?;++ let response = response_data+ .parse_xml::<boku::BokuResponse>()+ .into_report()+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+types::RouterData::try_from(types::ResponseRouterData {response,data: data.clone(),@@ -331,10 +390,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Paymedata: &types::PaymentsCaptureRouterData,res: Response,) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {- let response: boku::BokuPaymentsResponse = res- .response- .parse_struct("Boku PaymentsCaptureResponse")+ let response_data = String::from_utf8(res.response.to_vec())+ .into_report()+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;++ let response = response_data+ .parse_xml::<boku::BokuResponse>()+ .into_report().change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+types::RouterData::try_from(types::ResponseRouterData {response,data: data.clone(),@@ -370,10 +434,15 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponfn get_url(&self,- _req: &types::RefundsRouterData<api::Execute>,- _connectors: &settings::Connectors,+ req: &types::RefundsRouterData<api::Execute>,+ connectors: &settings::Connectors,) -> CustomResult<String, errors::ConnectorError> {- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())+ let boku_url = get_country_url(+ req.connector_meta_data.clone(),+ self.base_url(connectors).to_string(),+ )?;++ Ok(format!("{boku_url}/billing/3.0/refund-charge"))}fn get_request_body(@@ -383,7 +452,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponlet req_obj = boku::BokuRefundRequest::try_from(req)?;let boku_req = types::RequestBody::log_and_get_request_body(&req_obj,- utils::Encode::<boku::BokuRefundRequest>::encode_to_string_of_json,+ utils::Encode::<boku::BokuRefundRequest>::encode_to_string_of_xml,).change_context(errors::ConnectorError::RequestEncodingFailed)?;Ok(Some(boku_req))@@ -445,10 +514,28 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponsefn get_url(&self,- _req: &types::RefundSyncRouterData,- _connectors: &settings::Connectors,+ req: &types::RefundSyncRouterData,+ connectors: &settings::Connectors,) -> CustomResult<String, errors::ConnectorError> {- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())+ let boku_url = get_country_url(+ req.connector_meta_data.clone(),+ self.base_url(connectors).to_string(),+ )?;++ Ok(format!("{boku_url}/billing/3.0/query-refund"))+ }++ fn get_request_body(+ &self,+ req: &types::RefundSyncRouterData,+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {+ let req_obj = boku::BokuRsyncRequest::try_from(req)?;+ let boku_req = types::RequestBody::log_and_get_request_body(+ &req_obj,+ utils::Encode::<boku::BokuPaymentsRequest>::encode_to_string_of_xml,+ )+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;+ Ok(Some(boku_req))}fn build_request(@@ -472,10 +559,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponsedata: &types::RefundSyncRouterData,res: Response,) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {- let response: boku::RefundResponse =- res.response- .parse_struct("boku RefundSyncResponse")- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;+ let response: boku::BokuRsyncResponse = res+ .response+ .parse_struct("boku BokuRsyncResponse")+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;types::RouterData::try_from(types::ResponseRouterData {response,data: data.clone(),@@ -514,3 +601,43 @@ impl api::IncomingWebhook for Boku {Err(errors::ConnectorError::WebhooksNotImplemented).into_report()}}++fn get_country_url(+ meta_data: Option<Secret<serde_json::Value, WithType>>,+ base_url: String,+) -> Result<String, Report<errors::ConnectorError>> {+ let conn_meta_data: boku::BokuMetaData = meta_data+ .parse_value("Object")+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;++ Ok(base_url.replace('$', &conn_meta_data.country.to_lowercase()))+}++// validate xml format for the error+fn get_xml_deserialized(res: Response) -> CustomResult<ErrorResponse, errors::ConnectorError> {+ metrics::RESPONSE_DESERIALIZATION_FAILURE.add(+ &metrics::CONTEXT,+ 1,+ &[metrics::request::add_attributes("connector", "boku")],+ );++ let response_data = String::from_utf8(res.response.to_vec())+ .into_report()+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;++ // check for whether the response is in xml format+ match roxmltree::Document::parse(&response_data) {+ // in case of unexpected response but in xml format+ Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?,+ // in case of unexpected response but in html or string format+ Err(_) => {+ logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data);+ Ok(ErrorResponse {+ status_code: res.status_code,+ code: consts::NO_ERROR_CODE.to_string(),+ message: consts::UNSUPPORTED_ERROR_MESSAGE.to_string(),+ reason: Some(response_data),+ })+ }+ }+}diff --git a/crates/router/src/connector/boku/transformers.rs b/crates/router/src/connector/boku/transformers.rsindex 885ba5172d..8605bba32a 100644--- a/crates/router/src/connector/boku/transformers.rs+++ b/crates/router/src/connector/boku/transformers.rs@@ -1,107 +1,254 @@+use std::fmt;+use masking::Secret;use serde::{Deserialize, Serialize};+use url::Url;+use uuid::Uuid;use crate::{- connector::utils::PaymentsAuthorizeRequestData,+ connector::utils::{AddressDetailsData, RouterData},core::errors,+ services::{self, RedirectForm},types::{self, api, storage::enums},};-#[derive(Default, Debug, Serialize, Eq, PartialEq)]-pub struct BokuPaymentsRequest {- amount: i64,- card: BokuCard,+#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "kebab-case")]+pub enum BokuPaymentsRequest {+ BeginSingleCharge(SingleChargeData),+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "kebab-case")]+pub struct SingleChargeData {+ total_amount: i64,+ currency: String,+ country: String,+ merchant_id: Secret<String>,+ merchant_transaction_id: Secret<String>,+ merchant_request_id: String,+ merchant_item_description: String,+ notification_url: Option<String>,+ payment_method: String,+ charge_type: String,+ hosted: Option<BokuHostedData>,+}++#[derive(Debug, Clone, Serialize)]+pub enum BokuPaymentType {+ Dana,+ Momo,+ Gcash,+ GoPay,+ Kakaopay,+}++impl fmt::Display for BokuPaymentType {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Dana => write!(f, "Dana"),+ Self::Momo => write!(f, "Momo"),+ Self::Gcash => write!(f, "Gcash"),+ Self::GoPay => write!(f, "GoPay"),+ Self::Kakaopay => write!(f, "Kakaopay"),+ }+ }}-#[derive(Default, Debug, Serialize, Eq, PartialEq)]-pub struct BokuCard {- name: Secret<String>,- number: cards::CardNumber,- expiry_month: Secret<String>,- expiry_year: Secret<String>,- cvc: Secret<String>,- complete: bool,+#[derive(Debug, Clone, Serialize)]+pub enum BokuChargeType {+ Hosted,+}++impl fmt::Display for BokuChargeType {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::Hosted => write!(f, "hosted"),+ }+ }+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "kebab-case")]+struct BokuHostedData {+ forward_url: String,}impl TryFrom<&types::PaymentsAuthorizeRouterData> for BokuPaymentsRequest {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {match item.request.payment_method_data.clone() {- api::PaymentMethodData::Card(req_card) => {- let card = BokuCard {- name: req_card.card_holder_name,- number: req_card.card_number,- expiry_month: req_card.card_exp_month,- expiry_year: req_card.card_exp_year,- cvc: req_card.card_cvc,- complete: item.request.is_auto_capture()?,- };- Ok(Self {- amount: item.request.amount,- card,- })+ api_models::payments::PaymentMethodData::Wallet(wallet_data) => {+ Self::try_from((item, &wallet_data))}- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),+ _ => Err(errors::ConnectorError::NotSupported {+ message: format!("{:?}", item.request.payment_method_type),+ connector: "Boku",+ payment_experience: api_models::enums::PaymentExperience::RedirectToUrl.to_string(),+ })?,}}}-// Auth Struct+impl TryFrom<(&types::PaymentsAuthorizeRouterData, &api::WalletData)> for BokuPaymentsRequest {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(+ value: (&types::PaymentsAuthorizeRouterData, &api::WalletData),+ ) -> Result<Self, Self::Error> {+ let (item, wallet_data) = value;+ let address = item.get_billing_address()?;+ let country = address.get_country()?.to_string();+ let payment_method = get_wallet_type(wallet_data)?;+ let hosted = get_hosted_data(item);+ let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;+ let merchant_item_description = item.get_description()?;+ let payment_data = SingleChargeData {+ total_amount: item.request.amount,+ currency: item.request.currency.to_string(),+ country,+ merchant_id: auth_type.merchant_id,+ merchant_transaction_id: Secret::new(item.payment_id.to_string()),+ merchant_request_id: Uuid::new_v4().to_string(),+ merchant_item_description,+ notification_url: item.request.webhook_url.clone(),+ payment_method,+ charge_type: BokuChargeType::Hosted.to_string(),+ hosted,+ };++ Ok(Self::BeginSingleCharge(payment_data))+ }+}++fn get_wallet_type(wallet_data: &api::WalletData) -> Result<String, errors::ConnectorError> {+ match wallet_data {+ api_models::payments::WalletData::DanaRedirect { .. } => {+ Ok(BokuPaymentType::Dana.to_string())+ }+ api_models::payments::WalletData::MomoRedirect { .. } => {+ Ok(BokuPaymentType::Momo.to_string())+ }+ api_models::payments::WalletData::GcashRedirect { .. } => {+ Ok(BokuPaymentType::Gcash.to_string())+ }+ api_models::payments::WalletData::GoPayRedirect { .. } => {+ Ok(BokuPaymentType::GoPay.to_string())+ }+ api_models::payments::WalletData::KakaoPayRedirect { .. } => {+ Ok(BokuPaymentType::Kakaopay.to_string())+ }+ _ => Err(errors::ConnectorError::NotImplemented(+ "Payment method".to_string(),+ )),+ }+}+pub struct BokuAuthType {- pub(super) api_key: Secret<String>,+ pub(super) merchant_id: Secret<String>,+ pub(super) key_id: Secret<String>,}impl TryFrom<&types::ConnectorAuthType> for BokuAuthType {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {match auth_type {- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {- api_key: api_key.to_owned(),+ types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {+ merchant_id: key1.to_owned(),+ key_id: api_key.to_owned(),}),_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),}}}-// PaymentsResponse-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]-#[serde(rename_all = "lowercase")]-pub enum BokuPaymentStatus {- Succeeded,- Failed,- #[default]- Processing,+#[derive(Debug, Clone, Serialize)]+#[serde(rename = "query-charge-request")]+#[serde(rename_all = "kebab-case")]+pub struct BokuPsyncRequest {+ country: String,+ merchant_id: Secret<String>,+ merchant_transaction_id: Secret<String>,}-impl From<BokuPaymentStatus> for enums::AttemptStatus {- fn from(item: BokuPaymentStatus) -> Self {- match item {- BokuPaymentStatus::Succeeded => Self::Charged,- BokuPaymentStatus::Failed => Self::Failure,- BokuPaymentStatus::Processing => Self::Authorizing,- }+impl TryFrom<&types::PaymentsSyncRouterData> for BokuPsyncRequest {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {+ let address = item.get_billing_address()?;+ let country = address.get_country()?.to_string();+ let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;++ Ok(Self {+ country,+ merchant_id: auth_type.merchant_id,+ merchant_transaction_id: Secret::new(item.payment_id.to_string()),+ })}}-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]+// Connector Meta Data+#[derive(Debug, Clone, Deserialize)]+pub struct BokuMetaData {+ pub(super) country: String,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub enum BokuResponse {+ BeginSingleChargeResponse(BokuPaymentsResponse),+ QueryChargeResponse(BokuPsyncResponse),+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "kebab-case")]pub struct BokuPaymentsResponse {- status: BokuPaymentStatus,- id: String,+ charge_status: String, // xml parse only string to fields+ charge_id: String,+ hosted: Option<HostedUrlResponse>,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub struct HostedUrlResponse {+ redirect_url: Option<Url>,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename = "query-charge-response")]+#[serde(rename_all = "kebab-case")]+pub struct BokuPsyncResponse {+ charges: ChargeResponseData,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub struct ChargeResponseData {+ charge: SingleChargeResponseData,}-impl<F, T>- TryFrom<types::ResponseRouterData<F, BokuPaymentsResponse, T, types::PaymentsResponseData>>+#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub struct SingleChargeResponseData {+ charge_status: String,+ charge_id: String,+}++impl<F, T> TryFrom<types::ResponseRouterData<F, BokuResponse, T, types::PaymentsResponseData>>for types::RouterData<F, T, types::PaymentsResponseData>{type Error = error_stack::Report<errors::ConnectorError>;fn try_from(- item: types::ResponseRouterData<F, BokuPaymentsResponse, T, types::PaymentsResponseData>,+ item: types::ResponseRouterData<F, BokuResponse, T, types::PaymentsResponseData>,) -> Result<Self, Self::Error> {+ let (status, transaction_id, redirection_data) = match item.response {+ BokuResponse::BeginSingleChargeResponse(response) => get_authorize_response(response),+ BokuResponse::QueryChargeResponse(response) => get_psync_response(response),+ }?;+Ok(Self {- status: enums::AttemptStatus::from(item.response.status),+ status,response: Ok(types::PaymentsResponseData::TransactionResponse {- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),- redirection_data: None,+ resource_id: types::ResponseId::ConnectorTransactionId(transaction_id),+ redirection_data,mandate_reference: None,connector_metadata: None,network_txn_id: None,@@ -112,47 +259,95 @@ impl<F, T>}}+fn get_response_status(status: String) -> enums::AttemptStatus {+ match status.as_str() {+ "Success" => enums::AttemptStatus::Charged,+ "Failure" => enums::AttemptStatus::Failure,+ _ => enums::AttemptStatus::Pending,+ }+}++fn get_authorize_response(+ response: BokuPaymentsResponse,+) -> Result<(enums::AttemptStatus, String, Option<RedirectForm>), errors::ConnectorError> {+ let status = get_response_status(response.charge_status);+ let redirection_data = match response.hosted {+ Some(hosted_value) => Ok(hosted_value+ .redirect_url+ .map(|url| services::RedirectForm::from((url, services::Method::Get)))),+ None => Err(errors::ConnectorError::MissingConnectorRedirectionPayload {+ field_name: "redirect_url",+ }),+ }?;++ Ok((status, response.charge_id, redirection_data))+}++fn get_psync_response(+ response: BokuPsyncResponse,+) -> Result<(enums::AttemptStatus, String, Option<RedirectForm>), errors::ConnectorError> {+ let status = get_response_status(response.charges.charge.charge_status);++ Ok((status, response.charges.charge.charge_id, None))+}+// REFUND :-#[derive(Default, Debug, Serialize)]+#[derive(Debug, Clone, Serialize)]+#[serde(rename = "refund-charge-request")]pub struct BokuRefundRequest {- pub amount: i64,+ refund_amount: i64,+ merchant_id: Secret<String>,+ merchant_request_id: String,+ merchant_refund_id: Secret<String>,+ charge_id: String,+ reason_code: String,+}++#[derive(Debug, Clone, Serialize)]+pub enum BokuRefundReasonCode {+ NonFulfillment,+}++impl fmt::Display for BokuRefundReasonCode {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ Self::NonFulfillment => write!(f, "8"),+ }+ }}impl<F> TryFrom<&types::RefundsRouterData<F>> for BokuRefundRequest {type Error = error_stack::Report<errors::ConnectorError>;fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {- Ok(Self {- amount: item.request.refund_amount,- })+ let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;+ let payment_data = Self {+ refund_amount: item.request.refund_amount,+ merchant_id: auth_type.merchant_id,+ merchant_refund_id: Secret::new(item.request.refund_id.to_string()),+ merchant_request_id: Uuid::new_v4().to_string(),+ charge_id: item.request.connector_transaction_id.to_string(),+ reason_code: BokuRefundReasonCode::NonFulfillment.to_string(),+ };++ Ok(payment_data)}}-// Type definition for Refund Response-#[allow(dead_code)]-#[derive(Debug, Serialize, Default, Deserialize, Clone)]-pub enum RefundStatus {- Succeeded,- Failed,- #[default]- Processing,+#[derive(Debug, Clone, Deserialize)]+#[serde(rename = "refund-charge-response")]+pub struct RefundResponse {+ charge_id: String,+ refund_status: String,}-impl From<RefundStatus> for enums::RefundStatus {- fn from(item: RefundStatus) -> Self {- match item {- RefundStatus::Succeeded => Self::Success,- RefundStatus::Failed => Self::Failure,- RefundStatus::Processing => Self::Pending,- }+fn get_refund_status(status: String) -> enums::RefundStatus {+ match status.as_str() {+ "Success" => enums::RefundStatus::Success,+ "Failure" => enums::RefundStatus::Failure,+ _ => enums::RefundStatus::Pending,}}-#[derive(Default, Debug, Clone, Serialize, Deserialize)]-pub struct RefundResponse {- id: String,- status: RefundStatus,-}-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>for types::RefundsRouterData<api::Execute>{@@ -162,25 +357,69 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>) -> Result<Self, Self::Error> {Ok(Self {response: Ok(types::RefundsResponseData {- connector_refund_id: item.response.id.to_string(),- refund_status: enums::RefundStatus::from(item.response.status),+ connector_refund_id: item.response.charge_id,+ refund_status: get_refund_status(item.response.refund_status),}),..item.data})}}-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>+#[derive(Debug, Clone, Serialize)]+#[serde(rename = "query-refund-request")]+#[serde(rename_all = "kebab-case")]+pub struct BokuRsyncRequest {+ country: String,+ merchant_id: Secret<String>,+ merchant_transaction_id: Secret<String>,+}++impl TryFrom<&types::RefundSyncRouterData> for BokuRsyncRequest {+ type Error = error_stack::Report<errors::ConnectorError>;+ fn try_from(item: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {+ let address = item.get_billing_address()?;+ let country = address.get_country()?.to_string();+ let auth_type = BokuAuthType::try_from(&item.connector_auth_type)?;++ Ok(Self {+ country,+ merchant_id: auth_type.merchant_id,+ merchant_transaction_id: Secret::new(item.payment_id.to_string()),+ })+ }+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename = "query-refund-response")]+#[serde(rename_all = "kebab-case")]+pub struct BokuRsyncResponse {+ refunds: RefundResponseData,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub struct RefundResponseData {+ refund: SingleRefundResponseData,+}++#[derive(Debug, Clone, Deserialize)]+#[serde(rename_all = "kebab-case")]+pub struct SingleRefundResponseData {+ refund_status: String, // quick-xml only parse string as a field+ refund_id: String,+}++impl TryFrom<types::RefundsResponseRouterData<api::RSync, BokuRsyncResponse>>for types::RefundsRouterData<api::RSync>{type Error = error_stack::Report<errors::ConnectorError>;fn try_from(- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,+ item: types::RefundsResponseRouterData<api::RSync, BokuRsyncResponse>,) -> Result<Self, Self::Error> {Ok(Self {response: Ok(types::RefundsResponseData {- connector_refund_id: item.response.id.to_string(),- refund_status: enums::RefundStatus::from(item.response.status),+ connector_refund_id: item.response.refunds.refund.refund_id,+ refund_status: get_refund_status(item.response.refunds.refund.refund_status),}),..item.data})@@ -194,3 +433,14 @@ pub struct BokuErrorResponse {pub message: String,pub reason: Option<String>,}++#[derive(Debug, Serialize)]+pub struct BokuConnMetaData {+ country: String,+}++fn get_hosted_data(item: &types::PaymentsAuthorizeRouterData) -> Option<BokuHostedData> {+ item.return_url+ .clone()+ .map(|url| BokuHostedData { forward_url: url })+}diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rsindex 18e0265038..f020d50f80 100644--- a/crates/router/src/consts.rs+++ b/crates/router/src/consts.rs@@ -18,6 +18,7 @@ pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60;// String literalspub(crate) const NO_ERROR_MESSAGE: &str = "No error message";pub(crate) const NO_ERROR_CODE: &str = "No error code";+pub(crate) const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type";pub(crate) const CONNECTOR_UNAUTHORIZED_ERROR: &str = "Authentication Error from the connector";// General purpose base64 enginesdiff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rsindex 44e14c949c..d7d8897eeb 100644--- a/crates/router/src/types/api.rs+++ b/crates/router/src/types/api.rs@@ -284,7 +284,7 @@ impl ConnectorData {enums::Connector::Bambora => Ok(Box::new(&connector::Bambora)),enums::Connector::Bitpay => Ok(Box::new(&connector::Bitpay)),enums::Connector::Bluesnap => Ok(Box::new(&connector::Bluesnap)),- // enums::Connector::Boku => Ok(Box::new(&connector::Boku)), added as template code for future usage+ enums::Connector::Boku => Ok(Box::new(&connector::Boku)),enums::Connector::Braintree => Ok(Box::new(&connector::Braintree)),enums::Connector::Cashtocode => Ok(Box::new(&connector::Cashtocode)),enums::Connector::Checkout => Ok(Box::new(&connector::Checkout)),diff --git a/crates/router/tests/connectors/boku.rs b/crates/router/tests/connectors/boku.rsindex 132852f904..e971ad271e 100644--- a/crates/router/tests/connectors/boku.rs+++ b/crates/router/tests/connectors/boku.rs@@ -12,7 +12,7 @@ impl utils::Connector for BokuTest {use router::connector::Boku;types::api::ConnectorData {connector: Box::new(&Boku),- connector_name: types::Connector::DummyConnector1,+ connector_name: types::Connector::Boku,get_token: types::api::GetToken::Connector,}}diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.tomlindex 0ae7c40d42..22223275af 100644--- a/crates/router/tests/connectors/sample_auth.toml+++ b/crates/router/tests/connectors/sample_auth.toml@@ -167,4 +167,4 @@ api_key="API Key"[boku]api_key="API Key"-key1 = "transaction key"\ No newline at end of file+key1 = "MERCHANT ID"\ No newline at end of filediff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.jsonindex be30387845..4db52f964b 100644--- a/openapi/openapi_spec.json+++ b/openapi/openapi_spec.json@@ -3439,6 +3439,7 @@"bitpay","bambora","bluesnap",+ "boku","braintree","cashtocode","checkout",