博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WechatHelper
阅读量:4314 次
发布时间:2019-06-06

本文共 11022 字,大约阅读时间需要 36 分钟。

using System;using System.Collections.Generic;using System.Configuration;using System.IO;using System.Linq;using System.Net;using System.Text;using System.Web;using System.Web.Configuration;using System.Web.Mvc;using System.Web.Security;using System.Xml;using Newtonsoft.Json;using Travel.Business.Order;using Travel.WeChat.ViewModel.WeiPay;namespace Travel.WeChat.ToolClass{    public class WeChatPayHelper    {        ///         /// 微信客户端内部提交支付申请        ///         ///         /// 
[HttpGet] public static string GoToWeCharJSPay(Guid orderGuid, string token) { var weCharUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder"; var model = OrderInfoManager.Instance.GetById(orderGuid); unifiedorder unOrder = new unifiedorder(); unOrder.appid = ConfigurationManager.AppSettings["wx_appid"]; unOrder.mch_id = ConfigurationManager.AppSettings["wx_mch_id"]; unOrder.nonce_str = Guid.NewGuid().ToString().Replace("-", ""); unOrder.sign = ""; unOrder.body = model.ProductName; unOrder.out_trade_no = model.OrderCode; //payAmountmodel.PayAmount unOrder.total_fee = Convert.ToInt32(model.PayAmount * 100); unOrder.spbill_create_ip = GetWebClientIp(); unOrder.notify_url = ConfigurationManager.AppSettings["wechatUrl"] + "WeChatSite/WeChatPay/ProcessingCallback"; unOrder.trade_type = "JSAPI"; unOrder.openid = token; unOrder.device_info = "WEB"; var dc = new Dictionary
() { {
"appid",unOrder.appid}, {
"mch_id",unOrder.mch_id}, {
"total_fee",unOrder.total_fee}, {
"out_trade_no",unOrder.out_trade_no}, {
"body",unOrder.body}, {
"notify_url",unOrder.notify_url}, {
"trade_type",unOrder.trade_type}, {
"nonce_str",unOrder.nonce_str}, {
"spbill_create_ip",unOrder.spbill_create_ip}, {
"openid",unOrder.openid}, //{"scene_info","h5_info"} }; dc.Add("sign", GetSignString(dc));//签名 //2.将参数转换为xml格式 var sb = new StringBuilder(); sb.Append("
"); foreach (var d in dc) { sb.Append("<" + d.Key + ">" + d.Value + "
"); } sb.Append("
"); //应用场景信息 //1.创建请求连接 var request = (HttpWebRequest)WebRequest.Create(weCharUrl); //2.设置参数 var data = Encoding.UTF8.GetBytes(sb.ToString()); //4.设置属性 request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; //5.将转换后的参数以文件流的形式写入到请求中 using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } //6.声明变量,获取响应 var response = (HttpWebResponse)request.GetResponse(); //7.以文件流的方式读取响应结果 var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); // return responseString; } ///
/// 获取客户端ip /// ///
返回客户端IP地址
public static string GetWebClientIp() { HttpRequest request = HttpContext.Current.Request; string result = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; string a = request.UserHostAddress; if (String.IsNullOrEmpty(result)) { result = request.ServerVariables["REMOTE_ADDR"]; } if (String.IsNullOrEmpty(result)) { result = request.UserHostAddress; } if (String.IsNullOrEmpty(result)) { result = "0.0.0.0"; } return result; //string userIP = "IP"; //try //{ // if (System.Web.HttpContext.Current == null //|| System.Web.HttpContext.Current.Request == null //|| System.Web.HttpContext.Current.Request.ServerVariables == null) // return ""; // string CustomerIP = ""; // //CDN加速后取到的IP // CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"]; // if (!string.IsNullOrEmpty(CustomerIP)) // { // return CustomerIP; // } // CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; // if (!String.IsNullOrEmpty(CustomerIP)) // return CustomerIP; // if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) // { // CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; // if (CustomerIP == null) // CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; // } // else // { // CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; // } // if (string.Compare(CustomerIP, "unknown", true) == 0) // return System.Web.HttpContext.Current.Request.UserHostAddress; // return CustomerIP; //} //catch { } //return userIP; string user_IP; if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null) { user_IP = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString(); } else { user_IP = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString(); } return user_IP; } ///
/// 获取Sign签名 /// ///
键值对集合 ///
字符串类型的签名
public static string GetSignString(Dictionary
dic) { string key = WebConfigurationManager.AppSettings["wx_key"].ToString(); ;//商户平台 API安全里面设置的KEY 32位长度 //排序 dic = dic.OrderBy(d => d.Key).ToDictionary(d => d.Key, d => d.Value); //连接字段 var sign = dic.Aggregate("", (current, d) => current + (d.Key + "=" + d.Value + "&")); sign += "key=" + key; //MD5 sign = FormsAuthentication.HashPasswordForStoringInConfigFile(sign, "MD5").ToUpper(); return sign; } ///
/// 时间格式化 /// ///
///
public static string Format(DateTime date) { var dates = ""; dates += date.Year; dates += date.Month; dates += date.Date; dates += date.Hour; dates += date.Minute; dates += date.Second; return dates; } ///
/// 获取时间戳 /// ///
public static string GetTimeStamp() { TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalSeconds).ToString(); } #region 微信H5支付,外部浏览器调起支付 ///
/// 根据订单编号,提交订单到微信,获取跳转的地址 /// ///
订单编号 ///
要跳转的地址
[HttpPost] public static string PostToWeChar(Guid OrderGuid) { var model = OrderInfoManager.Instance.GetById(OrderGuid); var weCharUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder"; var si = new h5_info(); si.type = "Wap"; si.wap_url = ConfigurationManager.AppSettings["wechatUrl"]; si.wap_name = "驿马旅行"; var uo = new unifiedorder(); uo.appid = ConfigurationManager.AppSettings["wx_appid"]; uo.mch_id = ConfigurationManager.AppSettings["wx_mch_id"]; uo.total_fee = Convert.ToInt32(model.PayAmount) * 100;//单位元转换为分 uo.out_trade_no = model.OrderCode; uo.body = model.ProductName; uo.notify_url = ConfigurationManager.AppSettings["wechatUrl"] + "WeChatSite/Share/Pay"; uo.trade_type = "MWEB";//h5的支付类型 uo.nonce_str = Guid.NewGuid().ToString().Replace("-", ""); ;//随机字符串 uo.spbill_create_ip = GetWebClientIp(); var siJson = JsonConvert.SerializeObject(si); var dc = new Dictionary
() { {
"appid",uo.appid}, {
"mch_id",uo.mch_id}, {
"total_fee",uo.total_fee}, {
"out_trade_no",uo.out_trade_no}, {
"body",uo.body}, {
"notify_url",uo.notify_url}, {
"trade_type",uo.trade_type}, {
"nonce_str",uo.nonce_str}, {
"spbill_create_ip",uo.spbill_create_ip}, //{"scene_info","h5_info"} }; dc.Add("sign", GetSignString(dc));//签名 var sb = new StringBuilder(); sb.Append("
"); foreach (var d in dc) { if (d.Key == "scene_info") { sb.Append("<" + d.Key + ">{\"h5_info\":"); sb.Append(siJson); sb.Append("}
"); } else { sb.Append("<" + d.Key + ">" + d.Value + "
"); } } sb.Append("
"); //1.创建请求连接 var request = (HttpWebRequest)WebRequest.Create(weCharUrl); //2.设置参数 //var postData = "thing1=hello"; //postData += "&thing2=world"; //3.将参数转换编码格式 var data = Encoding.UTF8.GetBytes(sb.ToString()); //4.设置属性 request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = data.Length; //5.将转换后的参数以文件流的形式写入到请求中 using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } //6.声明变量,获取响应 var response = (HttpWebResponse)request.GetResponse(); //7.以文件流的方式读取响应结果 var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); var codeId = new XmlDocument(); codeId.LoadXml(responseString); //8.读取xml节点的值 XmlNode xn = codeId.SelectSingleNode("xml/mweb_url"); var mweb_url = xn.InnerText; //9.返回要跳转的url return mweb_url; } #endregion }}

 

转载于:https://www.cnblogs.com/JueXiaoQiang/p/7905435.html

你可能感兴趣的文章
CentOs7安装rabbitmq
查看>>
(转))iOS App上架AppStore 会遇到的坑
查看>>
解决vmware与主机无法连通的问题
查看>>
做好产品
查看>>
项目管理经验
查看>>
笔记:Hadoop权威指南 第8章 MapReduce 的特性
查看>>
JMeter响应数据出现乱码的处理-三种解决方式
查看>>
获取设备实际宽度
查看>>
Notes on <High Performance MySQL> -- Ch3: Schema Optimization and Indexing
查看>>
Alpha冲刺(10/10)
查看>>
数组Array的API2
查看>>
为什么 Redis 重启后没有正确恢复之前的内存数据
查看>>
No qualifying bean of type available问题修复
查看>>
第四周助教心得体会
查看>>
spfile
查看>>
Team Foundation Service更新:改善了导航和项目状态速查功能
查看>>
WordPress资源站点推荐
查看>>
Python性能鸡汤
查看>>
android Manifest.xml选项
查看>>
Cookie/Session机制具体解释
查看>>