.net 微信jssdk配置

Posted pengyinghao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.net 微信jssdk配置相关的知识,希望对你有一定的参考价值。

/// <summary>
/// 获取jssdk配置
/// </summary>
/// <returns></returns>
public IActionResult GetJSSDKConfig()
{
    string appid = ""; // appid
    string secret = ""; //appsecret
    string timestamp = GenerateTimeStamp();//时间戳
    string noncestr = GenerateNonceStr();//随机字符串
    string signature = "";//签名
    string url1 = $"https://api.weixin.qq.com/cgi-bin/token?    grant_type=client_credential&appid={appid}&secret={secret}";//获取token
    string result = Get(url1);
    JsonData jd = JsonMapper.ToObject(result);
    string access_token = (string)jd["access_token"];
    //2. 用第一步拿到的access_token 采用http GET方式请求获得jsapi_ticket(有效期7200    秒,开发者必须在自己的服务全局缓存jsapi_ticket)
    string url2 = $"https://api.weixin.qq.com/cgi-bin/ticket/getticket? access_token={access_token}&type=jsapi";//开发者临时票据
    string result2 = Get(url2);
    JsonData jd2 = JsonMapper.ToObject(result2);
    string ticket = (string)jd2["ticket"];
    //3. 开始签名
    string now_url = Get("nowUrl", "");
    string no_jiami = $"jsapi_ticket={ticket}&noncestr={noncestr}&timestamp={timestamp}&url={now_url}";
    //SHA1加密
    signature = EncryHelper.SHA1_Encrypt(no_jiami);
    var newData = new
        {
            appid,
            timestamp,
            noncestr,
            signature
         };
}

/// <summary>
/// 生成时间戳,标准北京时间,时区为东八区,自1970年1月1日 0点0分0秒以来的秒数
/// </summary>
/// <returns>时间戳</returns>
public  string GenerateTimeStamp()
{
    TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return Convert.ToInt64(ts.TotalSeconds).ToString();
}

/// <summary>
/// 生成随机串,随机串包含字母或数字
/// </summary>
/// <returns>随机串</returns>
public static string GenerateNonceStr()
{
    return Guid.NewGuid().ToString().Replace("-", "");
}

/// <summary>
/// 处理http GET请求,返回数据
/// </summary>
/// <param name="url">请求的url地址</param>
/// <returns>http GET成功后返回的数据,失败抛WebException异常</returns>
public  string Get(string url)
{
    System.GC.Collect();
    string result = "";
    HttpWebRequest request = null;
    HttpWebResponse response = null;
    //请求url以获取数据
    try
    {
        //设置最大连接数
        ServicePointManager.DefaultConnectionLimit = 200;
        //设置https验证方式
        if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
        {
            ServicePointManager.ServerCertificateValidationCallback =
                    new RemoteCertificateValidationCallback(CheckValidationResult);
        }
        /***************************************************************
        * 下面设置HttpWebRequest的相关属性
        * ************************************************************/
        request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        //设置代理
        //WebProxy proxy = new WebProxy();
        //proxy.Address = new Uri(WxPayConfig.PROXY_URL);
        //request.Proxy = proxy;
        //获取服务器返回
        response = (HttpWebResponse)request.GetResponse();
        //获取HTTP返回数据
        StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        result = sr.ReadToEnd().Trim();
        sr.Close();
    }
    catch (System.Threading.ThreadAbortException e)
    {
        Log.Error("HttpService","Thread - caught ThreadAbortException - resetting.");
        Log.Error("Exception message: {0}", e.Message);
        System.Threading.Thread.ResetAbort();
    }
    catch (WebException e)
    {
        Log.Error("HttpService", e.ToString());
        if (e.Status == WebExceptionStatus.ProtocolError)
        {
            Log.Error("HttpService", "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);
            Log.Error("HttpService", "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);
        }
        throw new WxPayException(e.ToString());
    }
    catch (Exception e)
    {
        Log.Error("HttpService", e.ToString());
        throw new WxPayException(e.ToString());
    }
    finally
    {
        //关闭连接和流
        if (response != null)
        {
            response.Close();
        }
        if (request != null)
        {
            request.Abort();
        }
    }
    return result;
}

以上是关于.net 微信jssdk配置的主要内容,如果未能解决你的问题,请参考以下文章

.NET 微信开发 JSSDK配置 wx.config调用 invalid signature签名错误分析

企业号微信支付 公众号支付 H5调起支付API示例代码 JSSDK C# .NET

ASP.NET MVC做的微信WEBAPP中调用微信JSSDK扫一扫

asp.net mvc 如何调用微信jssdk接口:分享到微信朋友(圈)| 分享到qq空间

asp.net mvc 如何调用微信jssdk接口:分享到微信朋友(圈)| 分享到qq空间

微信jssdk配置的问题,使用MVC制作的demo