Wechat applet payment C ා back end source code

Time:2020-6-28

The example of this article shares the back-end source code of wechat small program payment C ා for your reference. The specific content is as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Mvc_vue.Controllers
{
  public class wxController : Controller
  {
    //
    // GET: /wx/

    public ActionResult Index()
    {
      return View();
    }
    //Required value
    public static string _appid = "wxd930ea5d5a258f4f";
    public static string _mch_id = "10000100";
    public static string _key = "192006250b4c09247ec02edce69f6a2d";

    //Simulation Wx unified order openid (obtained from the foreground)
    public string getda(string openid)
    {
      return Getprepay_id(_appid, "shanghaifendian", "monixiaofei", _mch_id, GetRandomString(30), "http://www.weixin.qq.com/wxpay/pay.php", openid, getRandomTime(), 1);

    }

    

    //Wechat unified order to get prepay_ ID & sign again to return data
    private static string Getprepay_id(string appid, string attach, string body, string mch_id, string nonce_str, string notify_url, string openid, string bookingNo, int total_fee)
    {
      var url = " https://api.mch.weixin.qq.com/pay/unifiedorder "; // wechat unified order request address
      string strA = "appid=" + appid + "&attach=" + attach + "&body=" + body + "&mch_id=" + mch_id + "&nonce_str=" + nonce_str + "&notify_url=" + notify_url + "&openid=" + openid + "&out_trade_no=" + bookingNo + "&spbill_create_ip=61.50.221.43&total_fee=" + total_fee + "&trade_type=JSAPI";
      string strk = strA + "&key="+_ Key; // key the key set for the merchant platform (false)
      String strmd5 = MD5 (strk). Toupper(); // MD5 signature

      //String strhash = hmacsha256 ("sha256", strmd5). Toupper(); // only one signature method is needed (MD5 or hmacsha256 [pay documents need to be read carefully])

      //Signature
      var formData = "<xml>";
      formData += "<appid>" + appid + "</appid>";//appid 
      Formdata + = "< attach >" + attach + "< / attach >"; // additional data (description)
      Formdata + = "< body >" + body + "< / body >"; // product description
      formData += "<mch_ id>" + mch_ id + "</mch_ ID > "; // merchant number 
      formData += "<nonce_ str>" + nonce_ str + "</nonce_ STR > "; // random string, no longer than 32 bits. 
      formData += "<notify_ url>" + notify_ url + "</notify_ URL > "; // notification address
      formData += "<openid>" + openid + "</openid>";//openid
      formData += "<out_ trade_ no>" + bookingNo + "</out_ trade_ No > "; // merchant Order No. -- to be confirmed
      formData += "<spbill_ create_ ip>61.50.221.43</spbill_ create_ IP > "; // terminal IP -- user IP
      formData += "<total_ fee>" + total_ fee + "</total_ Fee > "; // the unit of payment is (min)
      formData += "<trade_ type>JSAPI</trade_ Type> "// transaction type (JSAPI-- official account payment)
      formData += "<sign>" + strMD5 + "</sign>"; //Signature
      formData += "</xml>";



      //Request data
      var getdata = sendPost(url, formData);

      //Get XML data
      XmlDocument doc = new XmlDocument();
      doc.LoadXml(getdata);
      //XML format to JSON
      string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc);



      JObject jo = (JObject)JsonConvert.DeserializeObject(json);
      string prepay_id = jo["xml"]["prepay_id"]["#cdata-section"].ToString();

      //Time stamp
      string _time = getTime().ToString();

      //Sign again to return data to applet
      string strB = "appId=" + appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + _time + "&key="_key;

      wx w = new wx();
      w.timeStamp = _time;
      w.nonceStr = nonce_str;
      w.package = "prepay_id=" + prepay_id;
      w.paySign = MD5(strB).ToUpper(); ;
      w.signType = "MD5";

      //Sending JSON data to applets
       return JsonConvert.SerializeObject(w);
    }

    /// <summary>
    ///Generate random string  
    /// </summary>
    ///< param name = "length" > string length < / param >
    /// <returns></returns>
    private static string GetRandomString(int length)
    {
      const string key = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
      if (length < 1)
        return string.Empty;

      Random rnd = new Random();
      byte[] buffer = new byte[8];

      ulong bit = 31;
      ulong result = 0;
      int index = 0;
      StringBuilder sb = new StringBuilder((length / 5 + 1) * 5);

      while (sb.Length < length)
      {
        rnd.NextBytes(buffer);

        buffer[5] = buffer[6] = buffer[7] = 0x00;
        result = BitConverter.ToUInt64(buffer, 0);

        while (result > 0 && sb.Length < length)
        {
          index = (int)(bit & result);
          sb.Append(key[index]);
          result = result >> 5;
        }
      }
      return sb.ToString();
    }

    /// <summary>
    ///Get timestamp
    /// </summary>
    /// <returns></returns>
    private static long getTime()
    {
      TimeSpan cha = (DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)));
      long t = (long)cha.TotalSeconds;
      return t;
    }


    /// <summary>
    ///MD5 signature method 
    /// </summary> 
    ///< param name = "inputtext" > encryption parameters < / param > 
    /// <returns></returns> 
    private static string MD5(string inputText)
    {
      MD5 md5 = new MD5CryptoServiceProvider();
      byte[] fromData = System.Text.Encoding.UTF8.GetBytes(inputText);
      byte[] targetData = md5.ComputeHash(fromData);
      string byte2String = null;

      for (int i = 0; i < targetData.Length; i++)
      {
        byte2String += targetData[i].ToString("x2");
      }

      return byte2String;
    }
    /// <summary>
    ///Hmac-sha256 signature method
    /// </summary>
    /// <param name="message"></param>
    /// <param name="secret"></param>
    /// <returns></returns>
    private static string HmacSHA256(string message, string secret)
    {
      secret = secret ?? "";
      var encoding = new System.Text.UTF8Encoding();
      byte[] keyByte = encoding.GetBytes(secret);
      byte[] messageBytes = encoding.GetBytes(message);
      using (var hmacsha256 = new HMACSHA256(keyByte))
      {
        byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
        return Convert.ToBase64String(hashmessage);
      }
    }

    /// <summary>
    ///Wx unified order request data
    /// </summary>
    ///< param name = "URL" > request address < / param >
    ///< param name = "urlargs" > parameters < / param >
    /// <returns></returns>
    private static string sendPost(string URL, string urlArgs)
    {
      //context.Request["args"]
      System.Net.WebClient wCient = new System.Net.WebClient();
      wCient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
      byte[] postData = System.Text.Encoding.ASCII.GetBytes("body=" + urlArgs);

      byte[] responseData = wCient.UploadData(URL, "POST", postData);

      string returnStr =  System.Text.Encoding . utf8. GetString (responsedata); // returns the accepted data 
      return returnStr;202     }

    /// <summary>
    ///Generate order number
    /// </summary>
    /// <returns></returns>
    private static string getRandomTime()
    {
      Random Rd = new random(); // used to generate random numbers
      string DateStr =  DateTime.Now.ToString ("yyyymmddhhmmsmm"); // date
      string str = DateStr +  rd.Next (10000). Tostring(). Padleft (4, '0'); // random number with date
      return str;
    }

  }
}

MVC. Net framework4 is used

Wechat applet payment front-end source code

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

Front end knowledge system

I have been on the road of the front end for more than three years. Because I am self-taught, I learned a lot of things, such as HTML, CSS and JavaScript at the beginning. I learned them seven or eight at the first time. I really can’t remember them. Later, I learned them again a […]