一、在支付前期,我们需要获取用户的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.net 微信支付 错误解决方案

    asp.net 微信支付 错误解决方案 在网上看到有人解决方案为: 解决方法 出现这种错误网上查出现有的原因是: 订阅号没有相关的权限 账号没有认证,没有相关的权限 那么这里遇到问题两种都不是.开发账 ...

  2. asp.net微信支付打通发货通知代码

    上次遇到微信支付,发货接口的时候,官方的demo也没有提供相应的代码 ,因本人技术有限,百度 google 很久都没有asp.net 版本的,最后只好硬着头皮自己搞,没想到官方文档也是错的. 我这一步 ...

  3. ASP.NET微信支付XXE漏洞修复

    1. XXE场景 关于XML解析存在的安全问题指引 微信支付商户,最近暴露的XML外部实体注入漏洞(XML External Entity Injection,简称 XXE),该安全问题是由XML组件 ...

  4. asp.net微信支付发起页面jsapi.aspx

    jsapi.aspx 后台核心代码 //创建支付应答对象 RequestHandler packageReqHandler = new RequestHandler(Context); //初始化 p ...

  5. Asp.Net微信支付接口之jsApiPay教程

      1.微信支付JsApiPay只能在微信浏览器中使用 2.必须先申请微信支付功能 3.设置域名 4.设置支付授权目录 一定要精确到最后一级目录 5.获取APPID和AppSecret AppSecr ...

  6. asp.net微信jsapi支付

    1.前台页面: <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"><head ru ...

  7. asp微信支付代码证书文件post_url.aspx和post_url.aspx.cs源码下载

    很多朋友在网上找的asp支付代码中都没有这两个证书文件,只能是用别人的,但是如果别人把他的网站这个文件删了,你的支付也就不能用了,今天我就把大家需要的这两个asp微信支付代码证书文件post_url. ...

  8. asp微信支付代码v4.1无需证书版,带回调入库的asp支付源码

    昨天帮一个客户写的,他的程序是老的asp,想实现微信在手机上下单付款,让帮忙给写一份asp微信支付的接口代码,昨天晚上闲着没事,搞了一个晚上才搞好,其实asp支付并不需要安装证书,其实asp支付也很好 ...

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

    原文:ASP.NET WEB API微信支付通知接口,返回xml数据,微信服务器不识别问题 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/MrTra ...

随机推荐

  1. 0x1L

    整形常量的后缀表示其类型,包括如下后缀,其中U和L的大小写通用 后缀        类型L           long int LL         long long int U          ...

  2. 应用git(SSH设置)

    git配置完成email和user后,才可以生成SSH Key. $ git config --global user.name "自定义名称" $ git config --gl ...

  3. C读写配置文件

    在项目开发中,经常需要读取应用配置文件的初始化参数,用于应用在启动前进行一些初始化配置.比如:Eclipse,参数项包含主题.字体大小.颜色.Jdk安装位置.自动提示等.Eclispe配置的文件格式是 ...

  4. jquery中each遍历对象和数组示例

    通用遍历方法,可用于遍历对象和数组.$().each(),回调函数拥有两个参数: 第一个为对象的成员或数组的索引,第二个为对应变量或内容.如需退出each循环可使回调函数返回false 现有如下两个s ...

  5. 判断是否为ie(包含ie11)

    if (!!window.ActiveXObject || "ActiveXObject" in window) { alert("IsIE"); }

  6. wget命令解析

           今天一学信息安全的同学让我编写一个软件,功能大致如下:输入网站首页,自动下载该网站所有网页并保存?拿到后感觉属于搜索引擎相关的,说实话我就感觉会用到递归,不过我不会写,百度也没找到资料, ...

  7. Codeforces Round #205 (Div. 2) : B

    如果某个数出现的次数大于或等于2次,那么平均分配到两个容器里面: 这里利用一个k来使得当出现次数为奇数时候分配得更加均匀: 剩下的就平均分配到两个容器里: 代码: #include<iostre ...

  8. Jamie's Contact Groups

    poj2289:http://poj.org/problem?id=2289 题意:给定一个规模为n的名单,要将名单中的人归到m个组中,给出每个人可能的分组号,需要确定一种分配方案,是的最大规模的组最 ...

  9. 创建range分区

    drop table T_PM_ACCT_DTL_AF_TEST; create table T_PM_ACCT_DTL_AF_TEST  (    DATA_DATE     date,    AC ...

  10. bzoj3504

    这是一道最大流的题目首先要引起注意的是,这类多个起点多个终点的问题一定要同时跑,不能分开来跑由于是无向图,也就相当于从起点跑2*n次好,不难想到s向两个起点连边,两终点想t连边,流量为2*an或2*b ...