本文转载自: http://www.cnblogs.com/imluzhi/p/4836216.html 作者:imluzhi 转载请注明该声明。

一、在支付前期,我们需要获取用户的OpenId,此块内容只针对于JSAPI(微信中直接支付)才需要,如果生成二维码(NATIVE)扫描支付,请跳过此步骤

思路大致是:获取用户的code值 > 根据code值再获取用户的OpenId

1、先绑定授权域名:开发者中心>网页服务>基础接口>网页授权获取用户基本信息>修改>设置网站的域名 。点击查看

2、获取用户的code值时,方式如下:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=&redirect_uri=&response_type=code&scope=&state=STATE#wechat_redirect

其中APPId不用多说,redirect_uri为网站的回调地址,回调地址必须UrlEncode处理,其中返回的参数就有code值

关于网页授权的两种scope的区别说明:snsapi_base和snsapi_userinfo,scope只有这2种方式

snsapi_base是不需要用户同意的,但是回调地址中获取到的code,根据这个code只能获取用户的OpenId,像:昵称,性别等是无法获取的,但是对于微信支付足够了

snsapi_userinfo是需要用户同意才能获取code,通过code能够获取用户的基本信息,这个做微信登录比较好,但是如果客户不同意就没办法进行下边的环节了,所以微信支付不要用这个参数。

3、根据2中返回的code值,获取用户的OpenId,方法如下:

方式:POST,Url:https://api.weixin.qq.com/sns/oauth2/access_token?appid=&secret=&code=&grant_type=authorization_code"

其中code值是从2中获取到的,返回参数为json,其中有一个参数为openid。

//1.获取Code值 string v = HttpContext.Current.Server.UrlEncode("http://****"); string url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=&redirect_uri=" + v + "&response_type=code&scope=snsapi_base#wechat_redirect"; Response.Redirect(url); string Code = base.QueryString("code"); //2.获取OpenId string urls = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=&secret=&code=" + Code + "&grant_type=authorization_code"; string openid = PostWebRequest(urls, ""); /// <summary> /// 获取OpenId方法 /// </summary> /// <param name="postUrl"></param> /// <param name="menuInfo"></param> /// <returns></returns> public string PostWebRequest(string postUrl, string menuInfo) { string returnValue = string.Empty; try { byte[] byteData = Encoding.UTF8.GetBytes(menuInfo); Uri uri = new Uri(postUrl); HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(uri); webReq.Method = "POST"; webReq.ContentType = "application/x-www-form-urlencoded"; webReq.ContentLength = byteData.Length; //定义Stream信息 Stream stream = webReq.GetRequestStream(); stream.Write(byteData, 0, byteData.Length); stream.Close(); //获取返回信息 HttpWebResponse response = (HttpWebResponse)webReq.GetResponse(); StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.Default); returnValue = streamReader.ReadToEnd(); //关闭信息  streamReader.Close(); response.Close(); stream.Close(); JsonTextParser parser = new JsonTextParser(); JsonObjectCollection obj = parser.Parse(returnValue) as JsonObjectCollection; JsonUtility.GenerateIndentedJsonText = false; string openid = obj["openid"].GetValue().ToString(); return openid; } catch (Exception ex) { return ex.ToString(); } }

二、微信支付

大致思路:微信支付>开发配置>支付授权目录  设置一个支付页面所在文件夹   点击查看相应位置

登录商户平台 > API安全 > 设置一个32位由数字和字母组成的密钥。  以上内容设置好后才可以进行支付参数的设置

1、引用微信JS  http://res.wx.qq.com/open/js/jweixin-1.0.0.js

2、设置config参数

3、设置chooseWXPay参数

4、支付

这里需要强调的是,下边config和chooseWXPay中的参数名为:nonceStr、timestamp要一直,否则就会一直报错:paySign加密错误

其中package的prepay_id参数内容的获取内容为可以根据官网的要求来,但传参字段一定要小写,一定要小写!

paySign 的加密方式为chooseWXPay的参数内容:timestamp、nonceStr、package、signType、key的组合加密,加密方式 和获取prepay_id的方式一样,具体操作看代码。但是这里的加密的参数的大小写要前后台对应一直,否则加密一定错误!

加密的方式如:把所有的参数首字母从小到大传参的形式组成字符串后,把key值再拼接上,具体内容请参考微信的签名算法和微信下单的参数列表

<script src="../js/jquery.js" type="text/javascript"></script> <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js" type="text/javascript"></script> <script type="text/javascript"> wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: '<%=appids %>', // 必填,公众号的唯一标识 timestamp: "<%=Timer %>", // 必填,生成签名的时间戳 nonceStr: "<%=RdCode %>", // 必填,生成签名的随机串 signature: "<%=GetSignature() %>", // 必填,签名,见附录1 jsApiList: ['chooseWXPay'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2  }); wx.ready(function () { wx.chooseWXPay({ appId: '<%=appids %>', timestamp: '<%=Timer %>', nonceStr: '<%=RdCode %>', package: 'prepay_id=<%=prepay_id %>', signType: 'MD5', paySign: '<%=paySign %>', success: function (res) { window.location.href = "cart4.aspx?Code=<%=Code %>"; }, cancel: function () { window.location.href = "cart3.aspx?Code=<%=Code %>"; }, error: function (e) { window.location.href = "cart3.aspx?Code=<%=Code %>"; } }); }); </script>
public string appids = "";//这里是公众号的AppId public string Code = ""; //订单号 public string Timer = "";//1970年到现在的秒数 public string OpenId = "";//用户的OpenId public string paySign = "";//paySign public string RdCode = "";//随机数 public string prepay_id = "";//package中prepay_id的值public string AppSecret = "";//公众号的AppSecret protected void Page_Load(object sender, EventArgs e) { GetTiks();  RdCode = getNoncestr().ToLower(); TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0); Timer = Convert.ToInt64(ts.TotalSeconds).ToString(); BindString(); }/// <summary>/// 获取jsapi_ticket的值/// </summary>public void GetTiks(){    string value = "";    Stream outstream = null;    Stream instream = null;    StreamReader sr = null;    HttpWebResponse response = null;    HttpWebRequest request = null;    Encoding encoding = Encoding.UTF8;    try    {        request = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + Get_Access_Token(appids, AppSecret) + "&type=jsapi");        CookieContainer cookieContainer = new CookieContainer();        request.CookieContainer = cookieContainer;        request.AllowAutoRedirect = true;        request.Method = "GET";        request.ContentType = "application/x-www-form-urlencoded";

        response = request.GetResponse() as HttpWebResponse;        request.GetResponse();        instream = response.GetResponseStream();        sr = new StreamReader(instream, encoding);        JsonTextParser parser = new JsonTextParser();        JsonObjectCollection obj = parser.Parse(sr.ReadToEnd().Replace("[]", "null")) as JsonObjectCollection;        JsonUtility.GenerateIndentedJsonText = false;        Tiks = obj["ticket"].GetValue().ToString();    }    catch (Exception ex)    {        Tiks = "";    }}/// <summary>/// 获取Access_Token值/// </summary>/// <param name="appid">AppId</param>/// <param name="secret">AppSecret</param>/// <returns></returns>public static string Get_Access_Token(string appid, string secret){    string value = "";

    Stream outstream = null;    Stream instream = null;    StreamReader sr = null;    HttpWebResponse response = null;    HttpWebRequest request = null;    Encoding encoding = Encoding.UTF8;    try    {

        request = (HttpWebRequest)WebRequest.Create("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret + "");        CookieContainer cookieContainer = new CookieContainer();        request.CookieContainer = cookieContainer;        request.AllowAutoRedirect = true;        request.Method = "GET";        request.ContentType = "application/x-www-form-urlencoded";

        response = request.GetResponse() as HttpWebResponse;        request.GetResponse();        instream = response.GetResponseStream();        sr = new StreamReader(instream, encoding);

        JsonTextParser parser = new JsonTextParser();

        JsonObjectCollection obj = parser.Parse(sr.ReadToEnd().Replace("[]", "null")) as JsonObjectCollection;        JsonUtility.GenerateIndentedJsonText = false;

        value = obj["access_token"].GetValue().ToString();

    }    catch (Exception ex)    {        value = "";    }    return value;}

/// <summary>/// config签名/// </summary>/// <returns></returns>public string GetSignature(){    string tmpStr = "jsapi_ticket=" + Tiks + "&noncestr=" + RdCode + "&timestamp=" + Timer + "&url=" + Request.Url.ToString();    return FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");

}

/// <summary>/// 客户端IP/// </summary>/// <param name="hc"></param>/// <returns></returns>public string GetIP(HttpContext hc){    string ip = string.Empty;

    try    {        if (hc.Request.ServerVariables["HTTP_VIA"] != null)        {            ip = hc.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();        }        else        {

            ip = hc.Request.ServerVariables["REMOTE_ADDR"].ToString();        }        if (ip == string.Empty)        {            ip = hc.Request.UserHostAddress;        }        return ip;    }    catch    {        return "";    }}

public static string getNoncestr(){    Random random = new Random();    return GetMD5(random.Next(1000).ToString(), "GBK");}

protected string getCharset(){    return Request.ContentEncoding.BodyName;}

/// <summary>/// 获取prepay_id/// </summary>/// <param name="postUrl"></param>/// <param name="menuInfo"></param>/// <returns></returns>public string PostWebRequests(string postUrl, string menuInfo){    string returnValue = string.Empty;    try    {        byte[] byteData = Encoding.UTF8.GetBytes(menuInfo);        Uri uri = new Uri(postUrl);        HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(uri);        webReq.Method = "POST";        webReq.ContentType = "application/x-www-form-urlencoded";        webReq.ContentLength = byteData.Length;        //定义Stream信息        Stream stream = webReq.GetRequestStream();        stream.Write(byteData, 0, byteData.Length);        stream.Close();        //获取返回信息        HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();        StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);        returnValue = streamReader.ReadToEnd();        //关闭信息        streamReader.Close();        response.Close();        stream.Close();

        XmlDocument doc = new XmlDocument();        doc.LoadXml(returnValue);        XmlNodeList list = doc.GetElementsByTagName("xml");        XmlNode xn = list[0];        string prepay_ids = xn.SelectSingleNode("//prepay_id").InnerText;        return prepay_ids;            //如果是二维码扫描,请返回下边的code_url,然后自己再更具内容生成二维码即可            //string code_url = xn.SelectSingleNode("//prepay_id").InnerText;            //return code_url;    }    catch (Exception ex)    {        return "";    }}

/// <summary>/// MD5/// </summary>/// <param name="encypStr"></param>/// <param name="charset"></param>/// <returns></returns>public static string GetMD5(string encypStr, string charset){    string retStr;    MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

    //创建md5对象    byte[] inputBye;    byte[] outputBye;

    //使用GB2312编码方式把字符串转化为字节数组.    try    {        inputBye = Encoding.GetEncoding(charset).GetBytes(encypStr);    }    catch (Exception ex)    {        inputBye = Encoding.GetEncoding("GB2312").GetBytes(encypStr);    }    outputBye = m5.ComputeHash(inputBye);

    retStr = System.BitConverter.ToString(outputBye);    retStr = retStr.Replace("-", "").ToUpper();    return retStr;}

public void BindString(){    //公众账号ID    string appid = appids;    //商品描述    string body = "订单号:" + order.Code;    //商户号    string mch_id = "***";    //随机字符串    string nonce_str = RdCode;    //通知地址-接收微信支付成功通知    string notify_url = "http://***/weixinnotify_url.aspx";    //用户标识 -用户在商户appid下的唯一标识    string openid = OpenId;    //商户订单号    string out_trade_no = order.Code;    //下单IP    string spbill_create_ip = GetIP(this.Context);    //总金额 分为单位    int total_fee = int.Parse(order.PayPrice.Value.ToString("0.00").Replace(".", ""));    //交易类型 -JSAPI、NATIVE、APP,如果是二维码扫描,请填写NATIVE,而且客户的OpenId可以不用传    string trade_type = "JSAPI";

    //微信签名    string tmpStr = "appid=" + appid + "&body=" + body + "&mch_id=" + mch_id + "&nonce_str=" + nonce_str + "&notify_url=" + notify_url + "&openid=" + openid + "&out_trade_no=" + out_trade_no + "&spbill_create_ip=" + spbill_create_ip + "&total_fee=" + total_fee + "&trade_type=" + trade_type + "&key=abc5465ouds65478dsaqw364879324ad";

    string Getprepay_idSign = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "MD5").ToUpper();

    string url = "https://api.mch.weixin.qq.com/pay/unifiedorder";    string xml = "<xml>";    xml += "<appid>" + appid + "</appid>";    xml += "<body>" + body + "</body>";    xml += "<mch_id>" + mch_id + "</mch_id>";    xml += "<nonce_str>" + nonce_str + "</nonce_str>";    xml += "<notify_url>" + notify_url + "</notify_url>";    xml += "<openid>" + openid + "</openid>";    xml += "<out_trade_no>" + out_trade_no + "</out_trade_no>";    xml += "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>";    xml += "<total_fee>" + total_fee + "</total_fee>";    xml += "<trade_type>" + trade_type + "</trade_type>";    xml += "<sign>" + Getprepay_idSign + "</sign>";    xml += "</xml>";    string v = PostWebRequests(url, xml);    //获取的prepay_id    prepay_id = v;    paySign = "";    string v_tmpStr = "appId=" + appid + "&nonceStr=" + RdCode + "&package=prepay_id=" + v + "&signType=MD5&timeStamp=" + Timer + "&key=abc5465ouds65478dsaqw364879324ad";    paySign = FormsAuthentication.HashPasswordForStoringInConfigFile(v_tmpStr, "MD5").ToUpper();}

下载源码

ASP.NET 微信支付相关推荐

  1. asp php微信支付,Asp微信支付接口代码 微信中生成订单后可以直接调出微信钱包直接付款_随便下源码网...

    Asp微信支付接口代码 微信中生成订单后,可以直接调出微信钱包直接付款 软件介绍: 众所周到,目前微信支付已经十分普及,无论是商场.超市.网站上,微信支付的发展十分迅速,而ASP版微信支付在微信公众平 ...

  2. 纯Asp实现微信支付

    微信支付的程序文件需要3个: (1)生成二唯码供用户扫描的网页: (2)支付回调URL,就是当用户扫描二唯码后,微信会调用这个回调用URL: (3)微信支付异步通知回调地址,当用户在微信上确认支付后, ...

  3. ASP 生成微信支付代码

    您可以使用 ASP.NET 来生成微信支付代码.首先,您需要在微信支付官方网站上申请账号并获得 API 密钥.然后,您可以使用微信支付 API 来生成微信支付代码,进行订单的创建.支付等操作. 具体实 ...

  4. ASP微信支付之扫码支付

    微信支付官网并没有提供ASP示例,以下针对的是ASP编程下接入微信支付接口中的扫码支付. http://blog.csdn.net/aminfo/article/details/48580107 一. ...

  5. ASP.NET WEB API微信支付通知接口,返回xml数据,微信服务器不识别问题

    最近开发微信小程序中用到了微信支付功能,接口开发用的ASP.NET WEB API: 在支付成功后,接口接受到微信服务器的支付通知结果,处理完数据,接口返回给微信服务数据时出现了问题. 微信服务器识别 ...

  6. asp.net 微信jsapi支付

    开始做jsapi支付时看了好多的demo及好多的博客感觉有大坑,果不其然,一点一点从坑中爬出. 前期准备,首先微信公众号中的配置,现在微信支付中配置好支付授权目录,先解释一下支付授权目录时做什么的,在 ...

  7. asp版微信公众号支付(包含源代码)

    微信支付网站需要接入的内容 微信小程序交流群:111733917 | 微信小程序从0基础到就业的课程:https://edu.csdn.net/topic/huangjuhua 需要准备的内容: 微信 ...

  8. ASP版微信小程序支付(包含源代码)

    asp版本的微信小程序支付里面代码的解说和各代码用途 微信小程序交流群:111733917 | 微信小程序从0基础到就业的课程:https://edu.csdn.net/topic/huangjuhu ...

  9. asp微信会员卡管理系统,超小的源码_带asp微信支付源码

    超微小的微信会员系统,可以在此基础上做无限开发,目前只有会员注册,获取微信用户信息入库,会员列表,微信支付,支付流水明细,判断是否登录,判断是否支付,如果支付了的会员则列出此会员的详细信息,id号,手 ...

最新文章

  1. php server script name,$_SERVER[SCRIPT_NAME]变量可值注入恶意代码
  2. jQuery实现文字向上滚动
  3. facebook 图像比赛_使用Facebook的Detectron进行图像标签
  4. 简单的C语言程序合集-2
  5. overline css,CSS text-decoration-line 属性
  6. JDK动态代理实现原理详解(源码分析)
  7. 用 或 || 取代常规 if - else 结构
  8. 51单片机数码管小数点c语言,求助一个51单片机控制的数码管计算器带小数点功能的...
  9. 总结(5)--- Numpy和Pandas库常用函数
  10. 3D渲染和动画制作KeyShot Pro for mac
  11. BIO、NIO、AIO差别
  12. 使用css的类名交集复合选择器 《转》
  13. 最强抓包神器 Fiddler 手机抓包详解
  14. BGP的基本配置以及路由聚合
  15. 计算机word的关闭怎么办,电脑无法打开Word提示已停止工作并自动退出怎么办
  16. lilo是什么意思_lilo是什么意思_lilo的用法_lilo造句_趣词词典
  17. android 标准时间格式,android开发中关于含有中文字段的格林尼治标准时间的时间格式转换...
  18. 新时代知识产权创新发展与严格保护_保护知识产权?宣传强化治理——东安街道团结社区新时代文明实践站大力宣传《知识产权法》...
  19. Sql like模糊查询 区分大小写
  20. PPT打不开提示访问出错怎么办

热门文章

  1. 托管资源和非托管资源
  2. 物流快递系统(java)
  3. dcom注册表问题修复
  4. JooMe:WiFi 分享中的无限可能
  5. 掌上好医APP的推广模式牛逼在哪
  6. 魔都上海4日旅游攻略?Python动态图告诉你!
  7. 如何成为一名成功的博士生(计算机科学(in NLPML))——Do what will make you happy
  8. 学计算机能把照片还原吗,计算机学生给乔碧萝p图,还原最高颜值,以下4张图谁可以毕业?...
  9. 【阿里云】秒懂云通信
  10. 将手机微信的图片打包成压缩包