专业网站建设品牌,十四年专业建站经验,服务6000+客户--广州京杭网络
免费热线:400-683-0016      微信咨询  |  联系我们

c# 微信h5支付

当前位置:网站建设 > 技术支持
资料来源:网络整理       时间:2023/2/14 0:57:59       共计:3624 浏览

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="play.aspx.cs" Inherits="qrcode_play" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>微信公众号支付</title>
<script type="text/javascript">
    //调用微信JS api 支付
    function jsApiCall(){
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest',
            <%=wxJsApiParam%>, //josn串
            function (res){
                WeixinJSBridge.log(res.err_msg);
                 if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                    window.location.href="<%=returnUrl%>"; //成功后跳转到提示页面
                 }
                
            }
        );
    }
    function callpay(){
        if (typeof WeixinJSBridge == "undefined"){
            if (document.addEventListener){
                document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
            }else if (document.attachEvent){
                document.attachEvent('WeixinJSBridgeReady', jsApiCall);
                document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
            }
        }else{
            jsApiCall();
        }
    }
    //页面加载完成后执行函数
    window.onload = callpay;
</script>
</head>

<body>
    <p><%=_response %></p>
    <p><%=wxJsApiParam %></p>
</body>
</html>



using ejk5;

using Maticsoft.Fn;
using OnlineAPI.App_Start;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;

public partial class qrcode_play : BasePage
{
    private string m = string.Empty;
    private string t = string.Empty;
    private string s = string.Empty;
    protected string wxJsApiParam = string.Empty;
    protected string returnUrl = "";
    protected string _response= string.Empty;
    protected Maticsoft.Model.SEO_ServiceOrder _ServiceOrder = new Maticsoft.Model.SEO_ServiceOrder();
    ILog _log = LogManager.GetLogger("qrcode_play");
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!string.IsNullOrEmpty(Request["code"]))
        {
            //根据appid,secret,code取到用户的全部信息
            Dictionary<string, object> dic = GetUserInfoByCode(WxPayConfig.GetConfig().GetAppID(), WxPayConfig.GetConfig().GetAppSecret(), Request["code"].ToString());
            if (dic.ContainsKey("errcode"))
            {
                //return Redirect("/WError/Index?Msg=" + dic["errmsg"].ToString());
                Response.Write(dic["errmsg"].ToString());
                Response.End();
            }
            string openid = dic["openid"].ToString();

            //JSAPI支付预处理
            try
            {
                _ServiceOrder = _bll_SEO_ServiceOrder.GetModelList(string.Format("SsOrderid='{0}'", Request["state"])).FirstOrDefault();
                if (_ServiceOrder == null)
                {
                    Response.Redirect("/404.html");
                    Response.End();
                }
                var total_fee = Convert.ToDouble(_ServiceOrder.PaidTotalPrice) * 100;
                //统一下单
                string sendUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
                JsApiConfig jsApiConfig = new JsApiConfig(0);
                WxPayData data = new WxPayData();
                data.SetValue("body", _ServiceOrder.Title); //商品描述
                data.SetValue("detail", _ServiceOrder.Title); //商品详情
                data.SetValue("out_trade_no", _ServiceOrder.SsOrderid); //商户订单号
                data.SetValue("total_fee", total_fee.ToString()); //订单总金额,以分为单位
                data.SetValue("trade_type", "JSAPI"); //交易类型
                data.SetValue("openid", openid); //公众账号ID
                data.SetValue("appid", WxPayConfig.GetConfig().GetAppID()); //公众账号ID
                data.SetValue("mch_id", WxPayConfig.GetConfig().GetMchID()); //商户号
                data.SetValue("nonce_str", JsApiPay.GenerateNonceStr()); //随机字符串
                data.SetValue("notify_url", "http://www.zybw.com/Handler/Notify_url.aspx"); //异步通知url
                data.SetValue("spbill_create_ip", GetIP()); //终端IP
                data.SetValue("sign", data.MakeSign(WxPayData.SIGN_TYPE_MD5)); //签名
                string xml = data.ToXml(); //转换成XML
                var startTime = DateTime.Now; //开始时间
                string response = HttpService.Post(xml, sendUrl, false, 6); //发送请求
                _log.Debug(response);
                _response = response;
                var endTime = DateTime.Now; //结束时间
                int timeCost = (int)((endTime - startTime).TotalMilliseconds); //计算所用时间
                WxPayData result = new WxPayData();
                result.FromXml(response, WxPayData.SIGN_TYPE_MD5);
                //JsApiPay.ReportCostTime(0, sendUrl, timeCost, result); //测速上报
                
                //获取H5调起JS API参数
                WxPayData jsApiParam = new WxPayData();
                jsApiParam.SetValue("appId", result.GetValue("appid"));
                jsApiParam.SetValue("timeStamp", JsApiPay.GenerateTimeStamp());
                jsApiParam.SetValue("nonceStr", JsApiPay.GenerateNonceStr());
                jsApiParam.SetValue("package", "prepay_id=" + result.GetValue("prepay_id"));
                jsApiParam.SetValue("signType", "MD5");
                jsApiParam.SetValue("paySign", jsApiParam.MakeSign(WxPayData.SIGN_TYPE_MD5));
                wxJsApiParam = jsApiParam.ToJson();
                //支付成功后跳转的URL
                returnUrl = "https://www.zybw.com/qrcode/sucess.aspx?orderid=" + _ServiceOrder.SsOrderid;
            }
            catch (Exception ex)
            {
                Response.Write("非法操作"+ex.Message);
                Response.End();
                return;
            }


        }
        else
        {
            m = Request.QueryString["orderid"];
            t = Request.QueryString["t"];
            s = Request.QueryString["s"];
            /*
            var key = Utils.EncryptAdmin(m + t);
            if (!key.Equals(s))
            {
                Response.Write("非法操作");
                Response.End();
            }
            */
            string redirect_uri = HttpUtility.UrlEncode("http://" + Request.Url.Authority + Request.Url.PathAndQuery);
            //return Redirect(string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state=STATE#wechat_redirect", AppId, redirect_uri, "snsapi_userinfo"));
            var url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect", WxPayConfig.GetConfig().GetAppID(), redirect_uri, "snsapi_userinfo", m);
            Response.Redirect(url);
        }


        
    }

    //因H5支付要求商户在统一下单接口中上传用户真实ip地址“spbill_create_ip”,故需要调用以下方法。
    public string GetIP()
    {
        HttpRequest request = HttpContext.Current.Request;
        string result = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        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;
    }
    /// <summary>
    /// 获得Code
    /// </summary>
    /// <typeparam name="T">表</typeparam>
    /// <returns></returns>
    protected long GetCode<T>()
    {
        Type type = typeof(T);
        return 0000;
        //return BLL.TSYS_Code.Instence.GetCode(type.Name);
    }

    /// <summary>
    ///用code换取获取用户信息(包括非关注用户的)(此access_token是网页授权的和普通无关)
    /// </summary>
    /// <param name="Appid"></param>
    /// <param name="Appsecret"></param>
    /// <param name="Code">回调页面带的code参数</param>
    /// <returns>获取用户信息(json格式)</returns>
    public Dictionary<string, object> GetUserInfoByCode(string Appid, string Appsecret, string Code)
    {
        JavaScriptSerializer Jss = new JavaScriptSerializer();
        string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code", Appid, Appsecret, Code);
        string ReText = WebRequestPostOrGet(url, "");//post/get方法获取信息
        Dictionary<string, object> DicText = (Dictionary<string, object>)Jss.DeserializeObject(ReText);
        if (!DicText.ContainsKey("openid"))
        {
            return DicText;
        }
        else
        {
            Dictionary<string, object> respDic = (Dictionary<string, object>)Jss.DeserializeObject(WebRequestPostOrGet("https://api.weixin.qq.com/sns/userinfo?access_token=" + DicText["access_token"] + "&openid=" + DicText["openid"] + "&lang=zh_CN", ""));
            return respDic;
        }
    }

    #region Post/Get提交调用抓取
    /// <summary>
    /// Post/get 提交调用抓取
    /// </summary>
    /// <param name="url">提交地址</param>
    /// <param name="param">参数</param>
    /// <returns>string</returns>
    public static string WebRequestPostOrGet(string sUrl, string sParam)
    {
        byte[] bt = System.Text.Encoding.UTF8.GetBytes(sParam);

        Uri uriurl = new Uri(sUrl);
        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uriurl);//HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + (url.IndexOf("?") > -1 ? "" : "?") + param);
        req.Method = "Post";
        req.Timeout = 120 * 1000;
        req.ContentType = "application/x-www-form-urlencoded;";
        req.ContentLength = bt.Length;

        using (Stream reqStream = req.GetRequestStream())//using 使用可以释放using段内的内存
        {
            reqStream.Write(bt, 0, bt.Length);
            reqStream.Flush();
        }
        try
        {
            using (WebResponse res = req.GetResponse())
            {
                //在这里对接收到的页面内容进行处理

                Stream resStream = res.GetResponseStream();

                StreamReader resStreamReader = new StreamReader(resStream, System.Text.Encoding.UTF8);

                string resLine;

                System.Text.StringBuilder resStringBuilder = new System.Text.StringBuilder();

                while ((resLine = resStreamReader.ReadLine()) != null)
                {
                    resStringBuilder.Append(resLine + System.Environment.NewLine);
                }

                resStream.Close();
                resStreamReader.Close();

                return resStringBuilder.ToString();
            }
        }
        catch (Exception ex)
        {
            return ex.Message;//url错误时候回报错
        }
    }
    #endregion Post/Get提交调用抓取
}
版权说明:
本网站凡注明“广州京杭 原创”的皆为本站原创文章,如需转载请注明出处!
本网转载皆注明出处,遵循行业规范,如发现作品内容版权或其它问题的,请与我们联系处理!
欢迎扫描右侧微信二维码与我们联系。
·上一条:C#微信H5支付 非微信内浏览器H5支付 浏览器微信支付 | ·下一条:C#支付宝支付接口H5版(手机网页支付)

Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有    粤ICP备16019765号 

广州京杭网络科技有限公司 版权所有