ASP.NET Core Web 支付功能接入 支付寶-電腦網頁支付篇

// 隨着版本更迭,新版本可能沒法徹底適用,請參考倉庫內的示例。git

這篇文章將介紹ASP.NET Core中使用 開源項目 Payment(https://github.com/Essensoft/Payment),實現接入支付寶-電腦網頁支付接口及同步跳轉及異步通知功能。github

開發環境:Win 10 x6四、VS2017 15.6.四、.NET Core SDK 2.1.10一、.NET Core Runtime 2.0.6json

1.新建"ASP.NET Core Web 應用程序"項目,我將它命名爲AlipaySample.app

2. 引入安裝Nuget包 "Essensoft.AspNetCore.Payment.Alipay". 目前(2018/03/29)版本爲 1.2.1異步

3. 在Startup.cs文件內 添加依賴注入、設置參數(螞蟻金服開放平臺 - 帳戶管理 - 密鑰管理 - 開放平臺密鑰)async

代碼:測試

 1         public void ConfigureServices(IServiceCollection services)
 2         {
 3             services.AddMvc();
 4 
 5             // 添加支付寶客戶端依賴注入
 6             services.AddAlipay();
 7 
 8             // 可在添加依賴注入時設置參數 通常設置 AppId、RsaPrivateKey、RsaPublicKey,其他默認便可.
 9             // 如:
10             //services.AddAlipay(opt =>
11             //{
12             //    //此處爲螞蟻金服開放平臺上建立的APPID,而非老版本的商戶號
13             //    opt.AppId = "";
14 
15             //    // 這裏的公私鑰 默認均爲支付寶官方推薦使用的RSAWithSHA256.
16             //    // 商戶私鑰
17             //    opt.RsaPrivateKey = "";
18             //    // 支付寶公鑰
19             //    opt.RsaPublicKey = "";
20             //});
21 
22             // 具體參數見 AlipayOptions
23 
24             // 註冊配置實例
25             services.Configure<AlipayOptions>(Configuration.GetSection("Alipay"));
26 
27             // 兩種方式設置註冊配置實例參數
28 
29             // 1.默認配置文件(開發環境/正式環境):
30             // appsettings.Development.json / appsettings.json
31 
32             // 2.用戶機密配置文件(VS2017 15.6.4 中,右鍵項目 => 管理用戶機密):
33             // Windows: % APPDATA %\microsoft\UserSecrets\< userSecretsId >\secrets.json
34             // Linux: ~/.microsoft / usersecrets /< userSecretsId >/ secrets.json
35             // macOS: ~/.microsoft / usersecrets /< userSecretsId >/ secrets.json
36 
37             // 配置文件內容以下('...'爲省略的項目其餘配置內容,如有的狀況下 -_-!):
38 
39             //{
40             // ...
41             // ...
42             //
43             //  "Alipay": {
44             //    "AppId": "",
45             //    "RsaPublicKey": "",
46             //    "RsaPrivateKey": ""
47             //  }
48             //}
49         }

4. 添加一個控制器, 我將其命名爲 AlipayController.cs網站

代碼:url

  1 using Essensoft.AspNetCore.Payment.Alipay;
  2 using Essensoft.AspNetCore.Payment.Alipay.Domain;
  3 using Essensoft.AspNetCore.Payment.Alipay.Notify;
  4 using Essensoft.AspNetCore.Payment.Alipay.Request;
  5 using Microsoft.AspNetCore.Mvc;
  6 using System.Threading.Tasks;
  7 
  8 namespace AlipaySample.Controllers
  9 {
 10     public class AlipayController : Controller
 11     {
 12         // 支付寶請求客戶端(用於處理請求與其響應)
 13         private readonly AlipayClient _client = null;
 14 
 15         // 支付寶通知客戶端(用於解析異步通知或同步跳轉)
 16         private readonly AlipayNotifyClient _notifyClient = null;
 17 
 18         // 賦值依賴注入對象
 19         public AlipayController(AlipayClient client, AlipayNotifyClient notifyClient)
 20         {
 21             _client = client;
 22             _notifyClient = notifyClient;
 23         }
 24 
 25         [HttpPost]
 26         public async Task<IActionResult> PagePay(string out_trade_no, string subject, string total_amount, string body, string product_code, string notify_url, string return_url)
 27         {
 28             // 組裝模型
 29             var model = new AlipayTradePagePayModel()
 30             {
 31                 Body = body,
 32                 Subject = subject,
 33                 TotalAmount = total_amount,
 34                 OutTradeNo = out_trade_no,
 35                 ProductCode = product_code,
 36             };
 37 
 38             var req = new AlipayTradePagePayRequest();
 39 
 40             // 設置請求參數
 41             req.SetBizModel(model);
 42 
 43             // 設置異步通知URL
 44             req.SetNotifyUrl(notify_url);
 45 
 46             // 設置同步跳轉URL
 47             req.SetReturnUrl(return_url);
 48 
 49             // 頁面請求處理 傳入 'GET' 返回的 response.Body 爲 URL, 'POST' 返回的 response.Body 爲 HTML.
 50             var response = await _client.PageExecuteAsync(req, null, "GET");
 51 
 52             // 重定向到支付寶電腦網頁支付頁面.
 53             return Redirect(response.Body);
 54         }
 55 
 56         /// <summary>
 57         /// 電腦網頁支付-同步跳轉
 58         /// 經常使用於展現訂單支付狀態頁,建議在異步通知統一作業務處理,而不是在此處.
 59         /// </summary>
 60         /// <returns></returns>
 61         [HttpGet]
 62         public async Task<IActionResult> PagePayReturn()
 63         {
 64             try
 65             {
 66                 // 以 AlipayTradePagePayReturnResponse 類型 解析
 67                 var notify = await _notifyClient.ExecuteAsync<AlipayTradePagePayReturnResponse>(Request);
 68                 return Content("成功:" + notify.OutTradeNo);
 69             }
 70             catch
 71             {
 72                 return Content("參數異常/驗籤失敗");
 73             }
 74         }
 75 
 76         /// <summary>
 77         /// 電腦網頁支付-異步通知
 78         /// 經常使用於訂單業務處理
 79         /// </summary>
 80         /// <returns></returns>
 81         [HttpPost]
 82         public async Task<IActionResult> PagePayNotify()
 83         {
 84             try
 85             {
 86                 // 以 AlipayTradePagePayNotifyResponse 類型 解析
 87                 var notify = await _notifyClient.ExecuteAsync<AlipayTradePagePayNotifyResponse>(Request);
 88                 if ("TRADE_SUCCESS" == notify.TradeStatus) // 訂單是否交易完成
 89                 {
 90                     // 業務代碼
 91                     // ...
 92                     // ...
 93 
 94                     //返回給支付寶成功內容,中止繼續通知
 95                     return Content("success", "text/plain");
 96                 }
 97                 // 訂單其餘狀態均返回給支付寶空內容.
 98                 return NoContent();
 99             }
100             catch
101             {
102                 // 參數異常/驗籤失敗均返回給支付寶空內容.
103                 return NoContent();
104             }
105         }
106     }
107 }

 5. 修改 Views/Home/Index 頁面,用於網站提交支付請求.spa

代碼:

 1 @{
 2     ViewData["Title"] = "Home Page";
 3 }
 4 
 5 <div style="padding:24px 0">
 6     <h3>支付寶 電腦網站支付 - <a href="https://docs.open.alipay.com/270/alipay.trade.page.pay" target="_blank">API文檔</a></h3>
 7     <hr />
 8     <form asp-controller="Alipay" asp-action="PagePay" target="_blank">
 9         <div class="form-group">
10             <label>body:</label>
11             <input type="text" class="form-control" name="body" value="支付寶網站支付測試詳情">
12         </div>
13         <div class="form-group">
14             <label>subject:</label>
15             <input type="text" class="form-control" name="subject" value="支付寶網站支付測試">
16         </div>
17         <div class="form-group">
18             <label>total_amount:</label>
19             <input type="text" class="form-control" name="total_amount" value="0.01">
20         </div>
21         <div class="form-group">
22             <label>out_trade_no:</label>
23             <input type="text" class="form-control" name="out_trade_no" value="@DateTime.Now.ToString("yyyyMMddHHmmssfff")">
24         </div>
25         <div class="form-group">
26             <label>product_code:</label>
27             <input type="text" class="form-control" name="product_code" value="FAST_INSTANT_TRADE_PAY">
28         </div>
29         <div class="form-group">
30             <label>notify_url(通知Url需外網環境可訪問):</label>
31             <input type="text" class="form-control" name="notify_url" value="http://xxx.com/alipay/pagepaynotify">
32         </div>
33         <div class="form-group">
34             <label>return_url:</label>
35             <input type="text" class="form-control" name="return_url" value="http://xxx.com/alipay/pagepayreturn">
36         </div>
37         <button type="submit" class="btn btn-primary">提交</button>
38     </form>
39 </div>

 實現頁面以下:

有疑問能夠在 https://github.com/Essensoft/Payment 提交Issue ,也能夠加入Payment 交流羣:522457525

本篇文章到此結束,具體效果可自行測試。感謝各位觀看。

相關文章
相關標籤/搜索