ASP.NET Core 2 Alipay scan code payment implementation code



Since Microsoft replaced its CEO, its strategic direction has changed a lot. It is no longer so closed. It has opened many things, embraced the open source community, realized cross platform by. Net, acquired xamarin and provided it to developers for free, etc. I like. Net very much and hope. Net core can rise. I started using. Net core 1.1, and now I use. Net core 2.0. . net core 2.0 has some changes compared with 1.1, and the API has been added a lot. It’s easier to use. I’m doing it recently Core docking Alipay, Baidu did not find out about Alipay’s core payment related information, so they studied it, the official server SDK modified to.Net standard 2. according to the official demo, we made a successful decision The payment demo of PC website of core 2.0 is described in the following article: ASP.NET Core 2 uses Alipay PC website to pay, you can take a look. Today I am talking about Alipay’s payment in face to face payment.

Brief introduction of scan code payment

Scan code payment is a payment method of Alipay face to face payment, which includes bar code payment, scan code payment and sound payment.

The scan code payment means that users open the sweep function of Alipay wallet and scan the two-dimensional code of a cash register scenario and pay the mode of payment. This mode is suitable for offline physical store payment, face-to-face payment and other scenarios.

Use example:

1. Recharge a live platform

2. A video website opens VIP

Scan code payment is more convenient and faster than the traditional jump web payment.

Business process:

Use steps:

  • The cashier operates the Alipay order and generates the two-dimensional code in the cash register system.
  • Users login Alipay wallet, click home page “payment sweep code pay” or click click “sweep” to enter the sweep interface.
  • The user scans the QR code provided by the cashier to check the amount and confirm the payment;
  • After the user pays, the merchant’s cashier system will get the result of payment success or failure.

For details, please refer to the official documents:

to configure

Create a ASP.NET Core 2.0 MVC project

Create a new configuration class, config

public class Config
 //Application ID, your appid
 public static string AppId = "";
 /// <summary>
 ///Cooperative merchant UID
 /// </summary>
 public static string Uid = "";
 // Alipay gateway
 public static string Gatewayurl = "";
 //Merchant private key, your original RSA private key
 public static string PrivateKey = "";
 // Alipay public key, view address:  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";

The following demonstration is the use of Alipay sandbox environment, Alipay sandbox environment refers to assist developers to interface function development and main function of auxiliary environment. 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

For a detailed description of the configuration, please see my previous article:ASP.NET Core 2 payment using Alipay PC website

ASP.NET Core 2.0 realizes code scanning payment

The component used to generate QR code is called qrcoder, which refers to a third-party implementation System.Drawing Class library, pay SDK face to face Alipay.AopSdk . f2fpay, which has been updated to GitHub and nuget. Nuget: ,github:

New controller ftfpaycontroller

1. Generate QR code action

/// <summary>
///Generate payment QR code
/// </summary>
///< param name = "ordername" > order name < / param >
///< param name = "orderamount" > order amount < / param >
///< param name = "outtradeno" > order No. < / param >
/// <returns></returns>
public IActionResult ScanCodeGen(string orderName, string orderAmount, string outTradeNo)
 AlipayTradePrecreateContentBuilder builder = BuildPrecreateContent(orderName,orderAmount,outTradeNo);
 //If you need to receive asynchronous notification of code scanning payment, please replace this line with the following two lines of comments.
 //It is recommended to use polling revocation mechanism instead of asynchronous notification to avoid unilateral account problems.
 AlipayF2FPrecreateResult precreateResult = _serviceClient.tradePrecreate(builder);
 //string notify_ url = " "; // merchant's address to receive asynchronous notification
 //AlipayF2FPrecreateResult precreateResult = serviceClient.tradePrecreate(builder, notify_url);
 //The processing of the following returned results is for reference.
 // payResponse.QrCode That is, the two-dimensional code for the link
 // link the two dimensional code to generate the two-dimensional code, and the customer can use Alipay wallet to scan the code.
 var bitmap = new Bitmap(Path.Combine(_hostingEnvironment.WebRootPath, "images/error.png"));
 switch (precreateResult.Status)
 case ResultEnum.SUCCESS:
  //Poll order results
  //According to the business needs, select whether to start a new thread for polling
  ParameterizedThreadStart parStart = new ParameterizedThreadStart(LoopQuery);
  Thread myThread = new Thread(parStart);
  object o = precreateResult.response.OutTradeNo;
 case ResultEnum.FAILED:
  Console.WriteLine (failed to generate QR Code:+ precreateResult.response.Body );
 case ResultEnum.UNKNOWN:
  Console.WriteLine (failed to generate QR Code: +( precreateResult.response  ==Null? "Configuration or network exception, please check and try again": "system exception, please update external order and restart request");
 MemoryStream ms = new MemoryStream();
 bitmap.Save(ms, ImageFormat.Png);
 byte[] bytes = ms.GetBuffer();
 return File(bytes, "image/png");

2. Construct payment request data

/// <summary>
///Construct payment request data
/// </summary>
///< param name = "ordername" > order name < / param >
///< param name = "orderamount" > order amount < / param >
///< param name = "outtradeno" > order No. < / param >
///< returns > request result set
private AlipayTradePrecreateContentBuilder BuildPrecreateContent(string orderName,string orderAmount,string outTradeNo)
 //When online joint debugging, please input the real external order number.
 if (string.IsNullOrEmpty(outTradeNo))
 outTradeNo = System.DateTime.Now.ToString("yyyyMMddHHmmss") + "0000" + (new Random()).Next(1, 10000).ToString();
 AlipayTradePrecreateContentBuilder builder = new AlipayTradePrecreateContentBuilder();
 //Collection account number
 builder.seller_id = Config.Uid;
 //Order number
 builder.out_trade_no = outTradeNo;
 //Total order amount
 builder.total_amount = orderAmount;
 //Amount involved in discount calculation
 //builder.discountable_amount = "";
 //Amount not involved in discount calculation
 //builder.undiscountable_amount = "";
 //Order name
 builder.subject = orderName;
 //Custom timeout
 builder.timeout_express = "5m";
 //Order description
 builder.body = "";
 //Store number, a very important parameter, can be used for subsequent marketing
 builder.store_id = "test store id";
 //Operator number, a very important parameter, can be used for later marketing
 builder.operator_id = "test";
 //Details of incoming product information
 List<GoodsInfo> gList = new List<GoodsInfo>();
 GoodsInfo goods = new GoodsInfo();
 goods.goods_id = "goods id";
 goods.goods_name = "goods name";
 goods.price = "0.01";
 goods.quantity = "1";
 builder.goods_detail = gList;
 //The system provider can fill in this parameter for commission return
 //ExtendParams exParam = new ExtendParams();
 //exParam.sysServiceProviderId = "20880000000000";
 //builder.extendParams = exParam;
 return builder;

3. Rendering QR code

/// <summary>
///Rendering QR code
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private Bitmap RenderQrCode(string str)
 QRCodeGenerator.ECCLevel eccLevel = QRCodeGenerator.ECCLevel.L;
 using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
 using (QRCodeData qrCodeData = qrGenerator.CreateQrCode(str, eccLevel))
  using (QRCode qrCode = new QRCode(qrCodeData))
  Bitmap bp= qrCode.GetGraphic(20, Color.Black, Color.White,
   new Bitmap(Path.Combine(_hostingEnvironment.WebRootPath, "images/alipay.png")), 15);
  return bp;

4. Polling payment results

/// <summary>
///Polling payment results
/// </summary>
///< param name = "O" > order No. < / param >
public void LoopQuery(object o)
 AlipayF2FQueryResult queryResult = new AlipayF2FQueryResult();
 int count = 100;
 int interval = 10000;
 string outTradeNo = o.ToString();
 for (int i = 1; i <= count; i++)
 queryResult = _serviceClient.tradeQuery(outTradeNo);
 if (queryResult?.Status == ResultEnum.SUCCESS)
/// <summary>
///Please add the processing after successful payment
/// </summary>
private void DoSuccessProcess(AlipayF2FQueryResult queryResult)
 //Payment succeeded, please update the corresponding documents
 Console.WriteLine (successful code scanning payment: merchant order number)+ queryResult.response.OutTradeNo );
/// <summary>
///Please add the processing after payment failure
/// </summary>
private void DoFailedProcess(AlipayF2FQueryResult queryResult)
 //Payment failed, please update the corresponding documents
 Console.WriteLine "Scan code payment failed: merchant order number"+ queryResult.response.OutTradeNo );

The above code is just for demonstration. In practice, please modify it according to your own needs. For example, polling should use one or more special background task threads instead of one thread for each order. Please note.

Demo demo

1. Generate QR code

To generate the QR code, three parameters must be provided: merchant order number, order amount and order name, otherwise errors will occur.

2. Scan payment

Open mobile phone Alipay, click Scan, scan two-dimensional code to complete payment.

If the sandbox environment is used, then the sandbox version of Alipay must be downloaded. With the official version of the two-dimensional code generated by Alipay scanning sandbox environment API, the two-dimensional code will fail, and the sandbox environment backstage can be downloaded. Sandbox account must be used in sandbox environment.

(1) After scanning:

(2) Successful payment:

3. Payment results

Results obtained by polling:

Address set

Previous article:ASP.NET Core 2 payment using Alipay PC website

Face to face official documents:

Nuget component:


Alipay.AopSdk . f2fpay:

Alipay pays the server SDK face to face.

In this paper, demo:


The above is the introduction of Xiaobian ASP.NET Core 2 Alipay scan code payment implementation code, we hope to help everyone, if you have any questions, please leave a message to me, Xiaobian will reply to you in time. Thank you very much for your support to developer!