2017-08-10 52 views
1

Authorize.NET提供了一個very thorough SDK.圍繞現有的API創建web api包裝器

您只需在您的解決方案安裝:

Install-Package AuthorizeNet 

我們需要的服務(S)來包裝AuthorizeNet API的所有功能。

爲了簡單起見,假設該API有下列方法:

public bool Pay(TransactionModel trans); 
public bool Decline(Guid id); 
public bool Refund(Guid id); 

我們可以很方便地從我們自己的解決方案控制器方法這些方法。例如:

[HttpPost] 
public bool PayAuthNet([FromBody] AuthnetTransModel model) 
{ 
    TransactionModel localTransModel = CreateLocalAuthModel(model); 
    var authNet = new AuthorizeNet(); 
    return authNet.Pay(localTransModel); 
} 

然而,API庫相當巨大,Authorize.NET暴露:

enter image description here

假設我們希望把它們包裝控制器,每個控制器到其自己的微服務(想對此方法的反饋),是否有更簡單的方法來包裝這些API中的每一個,迫使客戶端通過我們的包裝服務,而不是讓他們直接訪問Authorize.NET?

+2

難道不是所需要的信息脫身那個API已經是一個包裝了?爲什麼我們需要額外的層? – niksofteng

+0

因爲我的老闆說我們這樣做。我們希望允許客戶使用authorizenet,但通過一個非常「受控」的機制,並且我們要控制每個客戶可以訪問的內容等,這就是爲什麼我們需要一個包裝 –

+0

哇,這是相當廣泛的。就在我頭頂,你可以嘗試基於暴露的API和路由/漏斗命令來創建一個約定。但是我認爲很多工作不值得IMO做出努力。 – Nkosi

回答

1

這是一個簡單的解釋,因爲它太長了評論。

將使用僞代碼來演示包裹AuthorizeNet

使用在OP

[HttpPost] 
public bool PayAuthNet([FromBody] AuthnetTransModel model) 
{ 
    TransactionModel localTransModel = CreateLocalAuthModel(model); 
    var authNet = new AuthorizeNet(); 
    return authNet.Pay(localTransModel); 
} 

首先命名約定提供的例子。類似基於命名約定怎麼樣Name/Action映射到NameController.Action

PayAuthNet  --> AuthorizeNet.Pay 
DeclineAuthNet --> AuthorizeNet.Decline 
RefundAuthNet --> AuthorizeNet.Refund 

,然後利用反射的方法參數類型可確定,類似於AutoMapper是如何工作的映射功能MVC如何找到控制器將提供的模型轉換AuthnetTransModel到該函數的預期TransactionModel參數。

可以想像你可以使用表達式目錄樹從魔術字符串

public class BillingConroller : ApiController {  
    [HttpPost] 
    public bool PayAuthNet([FromBody] AuthnetTransModel model) { 
     return authorizeNetWrapper.Execute<BillingConroller>(c => c.PayAuthNet(model)); 
    }  
} 

在內部將檢查表達式樹中提取映射和執行匹配的包裹API

From expression tree: 
    Method being invoked: PayAuthNet 
    Argument provider:  AuthnetTransModel 
After applying convention: 
    Found matching method: AuthorizeNet.Pay 
    Expected arguement: TransactionModel 
Construct command 
    Create instance of TransactionModel and copy properties from provided model 
    Invoke => authNet.Pay(localTransModel)