c# 微信小程序支付模板

支付模板

 

public class PayHelper
    {

        public static readonly string appid = "wxd678efh567hg6787";
        public static readonly string mchid = "1490840662";
        public static readonly string key = "dfd547fab"; // 支付key

        /// 
        /// 统一支付
        /// 
        /// 支付金额
        /// 用户openid
        /// 订单号
        /// 订单内容
        /// 客户端ip
        /// 
        public static PayModel UnifiedOrder(int num, string openid, string orderNum, string bodyContent, string ip)
        {
            PayModel model = new PayModel();
            string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            string nonceStr = GetNonceStr();
            Dictionary dicParam = new Dictionary();
            dicParam.Add("appid", appid); // 应用程序id
            dicParam.Add("mch_id", mchid); // 商户id
            dicParam.Add("nonce_str", nonceStr); // 随机字符串
            dicParam.Add("body", bodyContent);
            dicParam.Add("out_trade_no", orderNum); // 单号
            dicParam.Add("total_fee", num.ToString()); // 支付金额
            dicParam.Add("spbill_create_ip", ip);
            dicParam.Add("notify_url", "https://blog.csdn.net/weixin_40411915"); // 回调
            dicParam.Add("trade_type", "JSAPI");
            dicParam.Add("openid", openid);

            string signValue = WxSignCalc(dicParam.ToList(), key);

            dicParam.Add("sign", signValue);
            var temp = dicParam.ToList();
            temp.Sort((item1, item2) => string.Compare(item1.Key, item2.Key));
            StringBuilder data = new StringBuilder();
            data.Append("");
            foreach (var item in temp)
            {
                data.Append($"<{item.Key}>{item.Value}");
            }
            data.Append("");

            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            //设置数据类型和长度
            request.ContentType = "text/xml";                              
            byte[] buf = System.Text.Encoding.UTF8.GetBytes(data.ToString());
            request.ContentLength = buf.Length;
            // 发送数据
            Stream reqStream = request.GetRequestStream();
            reqStream.Write(buf, 0, buf.Length);
            reqStream.Close();
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            string content = string.Empty;
            using (StreamReader rs = new StreamReader(response.GetResponseStream()))
            {
                content = rs.ReadToEnd();
            }
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(content);
            string returnCode = xml.GetElementsByTagName("return_code").Item(0).InnerText;
            if (returnCode == "FAIL")
                return model;

            string prepayId = xml.GetElementsByTagName("prepay_id").Item(0).InnerText;

            string timeStamp = Convert.ToInt64((DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds).ToString();

            List> datas = new List>() {
                    new KeyValuePair("appId", appid),
                    new KeyValuePair("timeStamp", timeStamp),
                    new KeyValuePair("nonceStr", nonceStr),
                    new KeyValuePair("package", "prepay_id="+prepayId),
                    new KeyValuePair("signType", "MD5")
                };
            model.paySign = WxSignCalc(datas, key);
            model.timeStamp = timeStamp;
            model.Package = "prepay_id=" + prepayId;
            model.NonceStr = nonceStr;
            model.signType = "MD5";

            return model;
        }

        /// 
        /// 获得随机字符串
        /// 
        /// 获取个数
        /// 
        private static string GetNonceStr(int num = 30)
        {
            Random random = new Random();
            string str = "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890";
            StringBuilder nonceStr = new StringBuilder();

            for (int i = 0; i < num; i++)
                nonceStr.Append(str[random.Next(0, str.Length)]);
            return nonceStr.ToString();
        }

        /// 
        /// 微信参数加密
        /// 
        /// 
        /// 
        /// 
        private static string WxSignCalc(List> param, string apiKey)
        {
            string signValue = string.Empty;
            StringBuilder data = new StringBuilder();
            // 1. 排序
            param.Sort((item1, item2) => string.Compare(item1.Key, item2.Key));

            // 2. 拼接
            param.ForEach(m =>
            {
                data.Append($"{m.Key}={m.Value}&");
            });
            data.Append("key=" + apiKey);

            // 3. 加密
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] buf = Encoding.UTF8.GetBytes(data.ToString());
            byte[] crypto = md5.ComputeHash(buf);
            signValue = BitConverter.ToString(crypto).Replace("-", "");
            return signValue;
        }
    }

 支付返回 Model

 public class PayModel
    {
        public string paySign { get; set; }
        public string timeStamp { get; set; }
        public string NonceStr { get; set; }
        public string Package { get; set; }
        public string signType { get; set; }
    }

调用案例

  1. 后台
[HttpPost]
public JsonResult OrderPay(string GUID, int num)
{
    string ip = string.Empty;
    if (!string.IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]))
        ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(',')[0]);
    if (string.IsNullOrEmpty(ip))
        ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
    if (string.IsNullOrEmpty(ip))
        ip = System.Web.HttpContext.Current.Request.UserHostAddress;

    PayModel payModel = PayHelper.UnifiedOrder(num * 100, OpenID, "yyyyMMddHHmmss", "小程序支付", ip);
    msg.Data = payModel;
    if (payModel.signType != null)
    {
        msg.Code = 1;
        msg.Msg = "支付创建成功";
    }
    return Json(msg);
}

2. 前台

wx.showLoading({
	title: '正在支付',
});
wx.request({
	url: "http://localhost:8080/Order/OrderPay",
	method: "POST",
	data: {
		gUID: "sljdkflskjdflsdskdjf",
		num: 12
	},
	header: { 'content-type': 'application/x-www-form-urlencoded' },
	success: function(res){
		if (res.data.Code === 1) {
			wx.requestPayment({
				'timeStamp': res.data.Data.timeStamp,
				'nonceStr': res.data.Data.NonceStr,
				'package': res.data.Data.Package,
				'signType': res.data.Data.signType,
				'paySign': res.data.Data.paySign,
				'success': function(res){
					wx.showToast({
						title: '支付成功',
					});
				},
				'fail': function(res){
					wx.showToast({
						title: '支付失败',
					});
				}
			});
		}else{
			wx.showToast({
				title: res.data.Msg,
			});
		}
	}, 
	fail: function(){
		wx.showLoading({
			title: '失败',
		});
	},
	complete: function(){
		wx.hideLoading();
	}
});



写在最后

这个模板测试了一下, 只需要改一下 appid, key, 商户号, 可以直接拿来使用.

本人小菜鸟, 代码写的有些垃圾, 各位笔下留字.

你可能感兴趣的:(C#)