SoFunction
Updated on 2025-03-06

Implement the payment function of WeChat Alipay based on C#

For the company's system business needs, I have learned about the interfaces of WeChat and Alipay scanning code payment in the past few days, and used C# to realize the functions of WeChat and Alipay scanning code payment.

WeChat payment is divided into 6 payment modes: 1. Payment code payment, payment, payment, payment, 5.h5 payment, 6. Mini program payment

What I am using here is native payment, which means that the web page generates a QR code and allows the user to scan the code to pay, and then calls the callback interface to determine whether the user has paid successfully.

There are also many Alipay payment APIs. I only use some of them that I can use in the system. Now I will simply record the code here, and start with WeChat Pay.

WeChat Payment

Go to the backend code first:

Pass in parameters (the total amount must be of int type, WeChat defaults to divisions), get the paid url, and then use the QR code generation tool to convert the url address into a QR code picture and stream the file back to the front desk

/**
 * Generate direct payment url, the payment url is valid for 2 hours, mode two
 * @param productId Product ID
 * @return Mode 2 URL
 */
public ActionResult GetPayUrl()
{
   //parameter   WxPayData data = new WxPayData();
   ("body", “test”);//Product Description   ("attach", "");//Add data   ("out_trade_no", ());//Random string   ("total_fee", 100);//lump sum   ("time_start", ("yyyyMMddHHmmss"));//Trading start time   ("time_expire", (10).ToString("yyyyMMddHHmmss"));//Trading end time   ("goods_tag", "");//Product Mark   ("trade_type", "NATIVE");//Trade Type   ("product_id", "1234");//Product ID   WxPayData result = (data);//Calling unified single interface   string url = ("code_url").ToString();//Get the QR code link returned by a unified single interface   var jsonData = new
   {
    url = (url)
   };
   return Success(jsonData);
    }

//Convert url to QR code picturepublic void CodeConversionTool(string str)
    {
      //Initialize the QR code generation tool      QRCodeEncoder qrCodeEncoder = new QRCodeEncoder();
       = QRCodeEncoder.ENCODE_MODE.BYTE;
       = QRCodeEncoder.ERROR_CORRECTION.M;
       = 0;
       = 4;
      //Generate QR code picture to string      Bitmap image = (str, );
      //Save as PNG to memory stream      MemoryStream ms = new MemoryStream();
      (ms, );
      //Output QR code picture      (());
      ();
    }

Front Desk Code:

$.lrSetForm(top.$.rootUrl + 'Test/GetPayUrl',function (data) {
          $("#img").attr("src",top.$.rootUrl + '/Test/CodeConversionTool?str=' + );
        });

Callback method:

public string WxPayNotify()
    {
      WePayReturnModel payResult = new WePayReturnModel();
      HttpContextBase context = (HttpContextBase)["MS_HttpContext"];//Get traditional context      HttpRequestBase request = ;//Define traditional request object      bool result = VerifyNotify(request, out payResult);
      if (result)
      {
        //Business code        /////////////////////////
        /////////////////////////
        //If it is successful, tell WeChat not to call the callback method again          WxPayData res = new WxPayData();
          ("transaction_id", );
          ("return_code", "SUCCESS");
          ("return_msg", "OK");
          return ();
      }
      else
      {
        return "fail";
      }
    }

Here are some things to note. The callback address is case-sensitive and must be used with post, and it does not support get. Moreover, whether it is WeChat or Alipay, in order to increase the chance of successful payment, we will make multiple callbacks. Therefore, after confirming that the user has successfully paid, we must return a result to tell WeChat that there is no need to make a callback.

Summarize

The above is what the editor introduced to you to realize the QR code scanning payment function based on C#. I hope it will be helpful to everyone. If you have any questions, please leave me a message. The editor will reply to everyone in time!