公众号jssdk使用代码

使用jssdk的时候,发生了在配置时候产生的问题。config:invalid signature

后来发现是因为地址配置错误产生的。

如果代码写完后,确认签名算法正确,可用http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign 页面工具进行校验。

 

参考网址:

  1. https://www.cnblogs.com/vipstone/p/6732660.html
  2. https://blog.csdn.net/dmw412724/article/details/81083058

 

我遇到的问题是

  1. 在生成签名(signature)的时候,生成出错了。是我的 window.location.href.split('#')[0]  手写的,应该动态获取。(建议全部小写)
  2. 在签名成功以后,傻傻的调用  wx.ready(function () {  })   一直没有执行。在这里也花费了好久时间

 

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js" type="text/javascript"></script>
    <script src="~/scripts/jquery/jquery-3.3.1/jquery-3.3.1.min.js"></script>
    <title>签到/签退</title>
    <script type="text/javascript">

        jQuery.post("/wxser/GetJSSDKConfig", {
            "url": encodeURIComponent(window.location.href.split('#')[0]),
            "t": new Date().getTime()
        }, function (result) {

            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: result.appId, // 必填,公众号的唯一标识
                timestamp: result.timestamp, // 必填,生成签名的时间戳
                nonceStr: result.nonceStr, // 必填,生成签名的随机串
                signature: result.signature,// 必填,签名,见附录1
                jsApiList: ['openLocation', 'getLocation'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
            });

            setTimeout(photo, 2000);
        });


        function photo() {
            wx.getLocation({
                type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
                success: function (res) {
                    var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90
                    var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。
                    var speed = res.speed; // 速度,以米/每秒计
                    var accuracy = res.accuracy; // 位置精度
                    if (latitude && longitude) {
                        $.ajax({
                            url: "/wxser/ClockInForAttendanceDo",
                            data: {
                                code: '@(Request.QueryString["code"])',
                                state: '@(Request.QueryString["state"])',
                                gps: longitude + ',' + latitude
                            },
                            success: function (res) {
                                document.write("<h2>" + res + "</h2>");
                            }
                        });
                    }
                }
            });
        }

    </script>
    <style>
        .btn0 {
            width: 80%;
            margin-top: 10px;
            height: 20px;
            background-color: burlywood;
            color: white;
            border-radius: 98px;
            display: none;
        }
    </style>
</head>
<body>
    <h2>正在签@(Request.QueryString["state"] == "1" ? "" : "退")...</h2>
    <div style="text-align:center;width:100%">
        <input type="button" value="打卡" id="gps" onclick="photo()" class="btn0" />
    </div>
</body>
</html>

 

[HttpPost]
public JsonResult GetJSSDKConfig(string url)
{
    Log.Debug("GetJSSDKConfig【url】:", Server.UrlDecode(url));
    string jsapi_ticket = WXSmartNote.Getjsapi_ticket();
    string timestamp = WXSmartNote.GetTimeStamp(), nonceStr = "scmone";   //timestamp 时间戳,nonceStr 加密码
    string str1 = string.Format(@"jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}"
                                , jsapi_ticket, nonceStr, timestamp, Server.UrlDecode(url));
    //获取签名
    string signature = WXSmartNote.GetSHA1(str1);
    Log.Debug("GetJSSDKConfig【signature】:", signature);
    ViewBag.appId = WxSmartNoteConfig.APPID;
    ViewBag.signature = signature;
    ViewBag.timestamp = timestamp;
    ViewBag.nonceStr = nonceStr;
    return this.Json(new
    {
        appId = WxSmartNoteConfig.APPID,
        signature = signature,
        timestamp = timestamp,
        nonceStr = nonceStr
    });
}




   public static string GetTimeStamp()
{
    TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return Convert.ToInt64(ts.TotalSeconds).ToString();
}


  public static string GetSHA1(string rawData)
{
    Log.Debug("签名源数据:", rawData);
    //创建SHA1签名类

    SHA1 sha1 = new SHA1CryptoServiceProvider();

    //编码用于SHA1验证的源数据

    byte[] source = Encoding.UTF8.GetBytes(rawData);

    //生成签名

    byte[] target = sha1.ComputeHash(source);

    //转化为string类型,注意此处转化后是中间带短横杠的大写字母,需要剔除横杠转小写字母

    string result = BitConverter.ToString(target).Replace("-", "").ToLower();

    //输出验证结果

    return result;

}


public static string Getjsapi_ticket()
{
    RedisHelper redis = new RedisHelper();
    string key_access = "access_token";
    string key_ticket = "ticket";
    string ticket = redis.StringGet(key_ticket);
    if (!string.IsNullOrEmpty(ticket))
    {
        return ticket;
    }
    else
    {
        string access_token = redis.StringGet(key_access);
        if (string.IsNullOrEmpty(access_token))
        {
            access_token = GetAccess_Token();
            redis.StringSet(key_access, access_token, TimeSpan.FromSeconds(7100));
        }
        if (string.IsNullOrEmpty(access_token)) return "";

        string url = string.Format("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi", access_token);

        var data = GetPage(url);
        Log.Debug("获取用户Access_Token GetAccess_Token", data);
        Dictionary<string, object> obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(data);

        object result = "";
        if (!obj.TryGetValue("ticket", out result))
            return "";
        ticket = result.ToString();
        redis.StringSet(key_ticket, ticket, TimeSpan.FromSeconds(7100));

        return ticket;
    }
}

 

posted @ 2019-11-28 16:28  Vincent_void  阅读(592)  评论(0编辑  收藏  举报