ASP.NET Core 2 uses Alipay PC website to pay for implementation code.

Time:2021-4-14

preface

Recently in use ASP.NET Core to develop, there is just a demand for access to Alipay payment, Baidu did not find the relevant information, see the official SDK and Demo are.NET Framework, so first, according to the official SDK source code, using.NET Standard 2 to achieve Alipay server SDK. Alipay.AopSdk.Core (github:https://github.com/stulzq/Alipay.AopSdk.Core), support. Net core 2.0. For convenience, it has been uploaded to nuget and can be used directly.

Alipay has more payment products, such as face to face payment, APP payment, mobile phone website payment, computer website payment, etc. this time, it is about computer website payment.

If you don’t have time to read the article, you can get the demo directly from GitHub to view it. It’s very simple. github:https://github.com/stulzq/Alipay.Demo.PCPayment

Create project

New one ASP.NET Core 2.0 MVC project

to configure

Because I did not apply for the interface when I was developing, I used Alipay sandbox environment to develop it.

Introduction to Alipay sandbox environment: ant sandbox environment (Beta) is an auxiliary environment that assists developers in developing interface functions and coordinating major functions. Sandbox environment simulates the main functions and main logic of some open platform products. Before the application online audit, developers can understand, combine and debug various open interfaces in sandbox environment according to their own needs, so as to help developers conduct online debugging and verification more quickly and smoothly after the application online audit I don’t have a job.
If you want to do integration testing before signing up or creating an application, you can use the sandbox environment.

Sandbox environment supports login with personal account or enterprise account.

Sandbox environment address:https://openhome.alipay.com/platform/appDaily.htm?tab=info

1. Generate key

Download the key generation tool provided by Alipay to generate.https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=105971&docType=1

2. Set the application public key

After we generate the key, we need to set up the application public key in the background of Alipay, which is the public key we generated.

After setting up, Alipay will give us a Alipay public key to save this Alipay public key.

This Alipay public key is different from the public key generated by ourselves. When we configure SDK, the public key we use is the Alipay public key.

3. Configure SDK

New oneConfigClass to store our configuration.

public class Config{ 
//Application ID, your appid 
public static string AppId = ""; 
// Alipay gateway 
public static string Gatewayurl = ""; 
//Merchant private key, your original RSA private key 
public static string PrivateKey = ""; 
// Alipay public key, view address: https://openhome.alipay.com/platform/keyManage.htm  The Alipay public key corresponding to APPID. 
public static string AlipayPublicKey = ""; 
 //Signature method 
public static string SignType = "RSA2"; 
//Coding format 
public static string CharSet = "UTF-8";}

Both ID and Alipay gateway can be viewed in Alipay backstage.

The private key of a business is the private key generated by us. The public key is the Alipay public key. We must pay attention to it and do not use it wrongly. Here, the public key and private key can be directly filled in the string.

Signature method recommendedRSA2Using RSA2, Alipay will use SHA256withRsa algorithm to check the interface when calling the interface (without restricting the length of key).

Encoding format: if we are directly configuring strings (public key and private key), then it is the encoding of our code. If we are using files (public key and private key), then it is the encoding of files.

The configuration is as follows:

Add SDK

Official SDK source code (.NET Framework), using.NET Standard 2 to achieve the Alipay server SDK. Alipay.AopSdk.Core (github:https://github.com/stulzq/Alipay.AopSdk.Core), support. Net core 2.0.
Install via nuget:Install-Package Alipay.AopSdk.Core

payment

Add a controllerPayController

///Initiate payment request // // < / summary > // < param name = "tradeno" > external order number, which is the only order number in the order system of merchant website < / param >/// 
< param name = "subject" > order name < / param > // / payment amount < / param >/// 
Product description < / param > // < returns > < / returns > [httppost]
public void PayRequest(string tradeno,string subject,string totalAmout,string itemBody){ 
DefaultAopClient 
client = new DefaultAopClient( Config.Gatewayurl ,  Config.AppId ,  Config.PrivateKey , "json", "2.0",  Config.SignType ,  Config.AlipayPublicKey ,  Config.CharSet , false); // assembly business parameter model alipaytradepagepaymodel = new alipaytradepagepaymodel(); 
model.Body = itemBody; 
model.Subject = subject; 
model.TotalAmount = totalAmout; 
model.OutTradeNo = tradeno; 
model.ProductCode = "FAST_INSTANT_TRADE_PAY"; AlipayTradePagePayRequest 
request = new AlipayTradePagePayRequest(); 
//Set synchronization callback address 
request.SetReturnUrl("http://localhost:5000/Pay/Callback"); 
 //Set asynchronous notification receiving address 
request.SetNotifyUrl(""); 
//Loading the business model into the request 
request.SetBizModel(model); 
var response =  client.SdkExecute (request);  Console.WriteLine ($"order payment initiated successfully, order number: {tradeno}"); 
// jump to Alipay payment 
Response.Redirect(Config.Gatewayurl + "?" + response.Body);}

function:

Figure 1

Figure 2

Figure 3

Payment asynchronous callback notification

Alipay’s synchronous callback notification (after jumping to the merchant website after payment is successful) is not reliable, so we must use asynchronous notification to get the payment result. The asynchronous notification is the address that Alipay actively asks us to provide. We check the data according to the request data and get the result of the payment.

// / <summary>/// payment asynchronous callback notification requires the configuration of the domain name because it is Alipay active post requesting the action to access the domain name or public network ip/// </summary>public async void Notify () { 
/*In the actual verification process, it is recommended that the merchant add the following verification. 
 1. The merchant needs to verify the out in the notification data_ trade_ No is the order number created in the merchant system, 
 2. Judge the total_ Whether the amount is the actual amount of the order (that is, the amount at the time of order creation), 
3. Seller in verification notification_ ID (or seller)_ Is email out_ trade_ No the corresponding operator of this document (sometimes, a merchant may have multiple sellers)_ id/seller_ email) 
 4. Verify app_ Whether the ID is the merchant itself. */ Dictionary<string, string> sArray = GetRequestPost(); 
if (sArray.Count != 0) 
 { 
bool flag = AlipaySignature.RSACheckV1(sArray, Config.AlipayPublicKey,Config.CharSet, Config.SignType, false); 
if (flag) 
{  
//Transaction status  
//Judge whether the order has been processed in the merchant website  
 //If not, according to the order number (out)_ trade_ No) check the details of the order in the order system of the merchant's website, and execute the merchant's business procedures  
//Be sure to determine the total at the time of request_ Amount and the total obtained at the time of notification_ Fee is consistent  
//If it has been processed, the business procedures of the merchant will not be implemented  
 //Note:  
// the refund date is longer than the refundable period (if three months can be refunded), the Alipay system sends the transaction status notification.  
Console.WriteLine(Request.Form["trade_status"]);  
await Response.WriteAsync("success"); 
 } 
else 
{  
await Response.WriteAsync("fail"); 
} 
 }}

Synchronous callback

Synchronous callback means the payment is successfully transferred back to the merchant website

function:

///< summary > // / payment synchronization callback // / < / summary > [httpget] public iationresult callback() {/ * in the actual verification process, it is recommended that merchants add the following verification. 
 1. The merchant needs to verify the out in the notification data_ trade_ No is the order number created in the merchant system, 
2. Judge the total_ Whether the amount is the actual amount of the order (that is, the amount at the time of order creation), 
3. Seller in verification notification_ ID (or seller)_ Is email out_ trade_ No the corresponding operator of this document (sometimes, a merchant may have multiple sellers)_ id/seller_ email) 
 4. Verify app_ Whether the ID is the merchant itself. */ Dictionary<string, string> sArray = GetRequestGet(); if ( sArray.Count  != 0) 
{ 
 bool flag = AlipaySignature.RSACheckV1(sArray, Config.AlipayPublicKey, Config.CharSet, Config.SignType, false); 
if (flag) 
{  
Console.WriteLine ($"synchronous verification passed, order No.: {sarray [" out_ trade_ no"]}");  
 Viewdata ["payresult"] = "synchronization verification passed";} else 
{  
Console.WriteLine ($"synchronization verification failed, order number: {sarray [" out_ trade_ no"]}");  
 Viewdata ["payresult"] = synchronization verification failed; 
 } 
} return View();
}

Order inquiry

Query the current status of the order: paid, unpaid, etc.

function:

Order refund


[HttpPost]public JsonResult Query(string tradeno, string alipayTradeNo){ 
 DefaultAopClient client = new DefaultAopClient(Config.Gatewayurl, Config.AppId, Config.PrivateKey, "json", "2.0", Config.SignType, Config.AlipayPublicKey, Config.CharSet, false); 
AlipayTradeQueryModel model = new AlipayTradeQueryModel(); 
 model.OutTradeNo = tradeno; 
model.TradeNo = alipayTradeNo; 
 AlipayTradeQueryRequest request = new AlipayTradeQueryRequest(); 
request.SetBizModel(model); 
var response = client.Execute(request); 
return Json(response.Body);}

Return the order amount.

function:

/// <summary>
///Order refund
// / </summary>/// <param name= "tradeno" > merchant order number </param>/// <param name= "alipayTradeNo" > Alipay transaction No. </param>/// <param name= "<param" > refund amount, "refund", "refund", "refund", "refund".  alipayTradeNo,string refundAmount,string refundReason,string refundNo){ DefaultAopClient client = new DefaultAopClient( Config.Gatewayurl ,  Config.AppId ,  Config.PrivateKey , "json", "2.0",  Config.SignType ,  Config.AlipayPublicKey ,  Config.CharSet , false); 
 AlipayTradeRefundModel model = new AlipayTradeRefundModel(); model.OutTradeNo = tradeno; model.TradeNo = alipayTradeNo; 
model.RefundAmount = refundAmount; model.RefundReason = refundReason; model.OutRequestNo = refundNo; AlipayTradeRefundRequest request = new AlipayTradeRefundRequest(); 
request.SetBizModel(model); 
 var response = client.Execute(request); return Json(response.Body);}

Refund inquiry

Check refund information.

function:

/// <summary>
///Refund inquiry
/// </summary>
///< param name = "tradeno" > merchant order number < / param >
// / <param name= "alipayTradeNo" > Alipay transaction No. </param>
///< param name = "refundno" > refund No. < / param >
/// <returns></returns>
[HttpPost]
public JsonResult RefundQuery(string tradeno,string alipayTradeNo,string refundNo)
{
 DefaultAopClient client = new DefaultAopClient(Config.Gatewayurl, Config.AppId, Config.PrivateKey, "json", "2.0",
  Config.SignType, Config.AlipayPublicKey, Config.CharSet, false);
 if (string.IsNullOrEmpty(refundNo))
 {
  refundNo = tradeno;
 }
 AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
 model.OutTradeNo = tradeno;
 model.TradeNo = alipayTradeNo;
 model.OutRequestNo = refundNo;
 AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
 request.SetBizModel(model);
 var response = client.Execute(request);
 return Json(response.Body);
}

Order closed

Close the order that has not been paid after a certain period of time. The order status should be: to be paid. The order that has been paid cannot be closed.

function:

/// <summary>
///Close order
/// </summary>
///< param name = "tradeno" > merchant order number < / param >
// / <param name= "alipayTradeNo" > Alipay transaction No. </param>
/// <returns></returns>
[HttpPost]
public JsonResult OrderClose(string tradeno, string alipayTradeNo)
{
 DefaultAopClient client = new DefaultAopClient(Config.Gatewayurl, Config.AppId, Config.PrivateKey, "json", "2.0",
  Config.SignType, Config.AlipayPublicKey, Config.CharSet, false);
 AlipayTradeCloseModel model = new AlipayTradeCloseModel();
 model.OutTradeNo = tradeno;
 model.TradeNo = alipayTradeNo;
 AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
 request.SetBizModel(model);
 var response = client.Execute(request);
 return Json(response.Body);
}

Address setAlipay API documentAlipay sandbox environmentAlipay key generation toolAlipay server SDK source codeAlipay server SDK Nuget

Most important:

In this paper, demo:https://github.com/stulzq/Alipay.Demo.PCPayment