隨著微軟的開源,越來越多的項目支持跨平臺,但是各種支付平臺提供的類庫,又老又不支持跨平臺,吐槽下,尤其是微信,還有好多坑,於是ICanPay誕生了,今天就來講ICanPay是什麼,怎麼使用? ICanPay是一個支持多商戶多種支付方式的跨平臺網關處理類庫,使用ICanPay可以簡化訂單的創建、查詢、 ...
隨著微軟的開源,越來越多的項目支持跨平臺,但是各種支付平臺提供的類庫,又老又不支持跨平臺,吐槽下,尤其是微信,還有好多坑,於是ICanPay誕生了,今天就來講ICanPay是什麼,怎麼使用?
ICanPay是一個支持多商戶多種支付方式的跨平臺網關處理類庫,使用ICanPay可以簡化訂單的創建、查詢、退款和接收網關返回的支付通知等操作。
目前支持的支付網關有:支付寶(Alipay)、微信支付(Wechatpay)、銀聯支付(Unionpay)
下麵以支付寶為例,其餘兩種支付,請參考Wiki
1. 配置商戶數據
1.在Startup中添加商戶數據
services.AddICanPay(a =>
{
var gateways = new Gateways();
var merchant = new Merchant
{
AppId = "",
NotifyUrl = "",
ReturnUrl = "",
AlipayPublicKey = "",
Privatekey = ""
};
gateways.Add(new AlipayGateway(merchant));
return gateways;
});
2.在Startup中使用ICanPay
app.UseICanPay();
以上就簡單的完成了對ICanPay的配置操作
2.支付
ICanPay支持多種支付方式,下麵就來講解如何使用
1.獲取支付網關
private readonly IGateways gateways;
public YourController(IGateways gateways)
{
this.gateways = gateways;
}
2.創建訂單
var order = new Order()
{
Amount = 0.01,
OutTradeNo = "訂單號",
Subject = "測試",
};
3.設置支付方式
var gateway = gateways.Get<AlipayGateway>(GatewayTradeType.Web);
4.支付
gateway.Payment(order);
特殊說明:GatewayTradeType.Barcode支付方式,需要再實現PaymentSucceed和PaymentFailed事件
3.非同步通知
1.獲取支付網關
private readonly IGateways gateways;
public NotifyController(IGateways gateways)
{
this.gateways = gateways;
}
2.實現支付通知事件
PaymentNotify notify = new PaymentNotify(gateways);
notify.PaymentSucceed += Notify_PaymentSucceed;
notify.PaymentFailed += Notify_PaymentFailed;
notify.UnknownGateway += Notify_UnknownGateway;
private void Notify_PaymentSucceed(object sender, PaymentSucceedEventArgs e)
{
// 支付成功時時的處理代碼
/* 建議添加以下校驗。
* 1、需要驗證該通知數據中的OutTradeNo是否為商戶系統中創建的訂單號,
* 2、判斷Amount是否確實為該訂單的實際金額(即商戶訂單創建時的金額),
*/
if (e.GatewayType == typeof(AlipayGateway))
{
var notify = (Notify)e.Notify;
}
}
private void Notify_PaymentFailed(object sender, PaymentFailedEventArgs e)
{
// 支付失敗時的處理代碼
}
private void Notify_UnknownGateway(object sender, UnknownGatewayEventArgs e)
{
// 無法識別支付網關時的處理代碼
}
3.接收支付通知
await notify.ReceivedAsync();
4.輔助介面
1.查詢
var notify = (Notify)gateway.Query(new Auxiliary
{
OutTradeNo = "訂單號"
});
2.撤銷
var notify = (Notify)gateway.Cancel(new Auxiliary
{
OutTradeNo = "訂單號"
});
3.關閉
var notify = (Notify)gateway.Close(new Auxiliary
{
OutTradeNo = "訂單號"
});
4.退款
var notify = (Notify)gateway.Refund(new Auxiliary
{
OutTradeNo = "訂單號",
RefundAmount = 123,
OutRefundNo = "退款單號"
});
5.退款查詢
var notify = (Notify)gateway.RefundQuery(new Auxiliary
{
OutTradeNo = "訂單號",
OutRefundNo = "退款單號"
});
6.對賬單下載
gateway.BillDownload(new Auxiliary
{
BillType = "trade",
BillDate = "2017-10-31"
});
以上就簡單的講解瞭如何使用ICanPay,如果有什麼問題,也可以在Github上提問。
項目地址:ICanPay