微信小程序支付C#后端源码

作者:oneall 时间:2023-11-21 15:06:29 

本文实例为大家分享了微信小程序支付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 Framework4

微信小程序支付前端源码

来源:https://www.cnblogs.com/oneall/p/9548722.html

标签:C#,微信小程序,支付
0
投稿

猜你喜欢

  • Java并发控制机制详解

    2022-12-12 22:07:56
  • C#创建、部署、调用WebService图文实例详解

    2022-05-03 06:35:20
  • java实现Xml与json之间的相互转换操作示例

    2023-06-21 13:30:39
  • Autowired的注入过程源码解析

    2022-04-29 17:53:36
  • Android使用ViewPager实现类似laucher左右拖动效果

    2022-05-18 20:33:59
  • android studio节省C盘空间的配置方法

    2023-07-04 16:43:20
  • java高并发的并发级别详解

    2023-08-05 15:44:38
  • Spring Cloud 整合 nacos实现动态配置中心的详细步骤

    2023-01-19 18:15:00
  • 详解Android中实现ListView左右滑动删除条目的方法

    2021-08-15 03:38:53
  • Java项目导入IDEA的流程配置以及常见问题解决方法

    2021-11-21 10:02:24
  • Android 中 EventBus 的使用之多线程事件处理

    2021-09-14 13:34:12
  • java emoji表情存储的解决方法

    2023-07-10 20:19:06
  • C#实现自定义windows系统日志的方法

    2021-12-17 13:02:31
  • Java overload和override的区别分析

    2023-10-12 15:16:17
  • Android ListView实现简单列表功能

    2022-11-29 12:35:18
  • JAVA中SpringBoot启动流程分析

    2021-07-03 03:57:05
  • C#开发WinForm清空DataGridView控件绑定的数据

    2022-12-01 11:22:08
  • 详解Android实现定时器的几种方法

    2021-10-17 17:37:17
  • android 判断横竖屏问题的详解

    2022-07-28 08:37:13
  • WinForm之BindingSource基础操作实例教程

    2021-10-18 07:37:59
  • asp之家 软件编程 m.aspxhome.com