위 챗 애플 릿 결제 C\#백 엔 드 소스 코드

본 논문 의 사례 는 위 챗 애플 릿 결제 C\#백 엔 드 소스 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.

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();
    }
    //   
    public static string _appid = "wxd930ea5d5a258f4f";
    public static string _mch_id = "10000100";
    public static string _key = "192006250b4c09247ec02edce69f6a2d";

    //  wx     openid(    )
    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);

    }

    

    //        prepay_id &         
    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";//          
      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          key( )
      string strMD5 = MD5(strk).ToUpper();//MD5  

      //string strHash=HmacSHA256("sha256",strmd5).ToUpper();  //        (MD5   HmacSHA256   【        】)

      //  
      var formData = "<xml>";
      formData += "<appid>" + appid + "</appid>";//appid 
      formData += "<attach>" + attach + "</attach>"; //    (  )
      formData += "<body>" + body + "</body>";//    
      formData += "<mch_id>" + mch_id + "</mch_id>";//    
      formData += "<nonce_str>" + nonce_str + "</nonce_str>";//     ,   32 。 
      formData += "<notify_url>" + notify_url + "</notify_url>";//    
      formData += "<openid>" + openid + "</openid>";//openid
      formData += "<out_trade_no>" + bookingNo + "</out_trade_no>";//       -- 
      formData += "<spbill_create_ip>61.50.221.43</spbill_create_ip>";//  IP --  ip
      formData += "<total_fee>" + total_fee + "</total_fee>";//       ( )
      formData += "<trade_type>JSAPI</trade_type>";//    (JSAPI--     )
      formData += "<sign>" + strMD5 + "</sign>"; //  
      formData += "</xml>";



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

      //  xml  
      XmlDocument doc = new XmlDocument();
      doc.LoadXml(getdata);
      //xml   json
      string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(doc);



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

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

      //            
      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";

      //      json  
       return JsonConvert.SerializeObject(w);
    }

    /// <summary>
    ///        
    /// </summary>
    /// <param name="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>
    ///      
    /// </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     
    /// </summary> 
    /// <param name="inputText">    </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    
    /// </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        
    /// </summary>
    /// <param name="URL">    </param>
    /// <param name="urlArgs">  </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);//        
      return returnStr;202     }

    /// <summary>
    ///      
    /// </summary>
    /// <returns></returns>
    private static string getRandomTime()
    {
      Random rd = new Random();//       
      string DateStr = DateTime.Now.ToString("yyyyMMddHHmmssMM");//  
      string str = DateStr + rd.Next(10000).ToString().PadLeft(4, '0');//       
      return str;
    }

  }
}
MVC.NET Framework 4 를 사 용 했 습 니 다.
위 챗 애플 릿 결제 전단 소스 코드
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기