ASP.NET 微信支付

一、在支付前期,我们需要获取用户的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();
}

 下载源码

posted @ 2015-09-28 17:38  imluzhi  阅读(34787)  评论(9编辑  收藏  举报