开发者社区> 问答> 正文

请求后台取不到code值获得userId有问题,一直验证失败(.NET)

前端代码:

<script type="text/javascript">  
        var _config = <%= GetConfig() %>;  
        </script>  
    <script type="text/javascript" src="../javascripts/zepto.min.js">  
        </script>  
    <script type="text/javascript" src="https://g.alicdn.com/ilw/ding/0.9.2/scripts/dingtalk.js" ></script>
    <script type="text/javascript">
      
        dd.config({                                                          //实现验证  
            agentId : _config.agentId,  
            corpId : _config.corpId,  
            timeStamp : _config.timeStamp,  
            nonceStr : _config.nonceStr,  
            signature : _config.signature,  
            jsApiList : [  
                    'runtime.info',  
                    'biz.contact.choose',  
                    'device.notification.confirm',  
                    'device.notification.alert',  
                    'device.notification.prompt',  
                    'biz.ding.post',  
                    'biz.util.openLink' ]  
        });  
  
        dd.ready(function() {                                               //验证成功  
  
            dd.runtime.permission.requestAuthCode({                         //获取code码值  
                corpId : _config.corpId,  
                onSuccess : function(info) {  
                    alert('authcode: ' + info.code);  
                    $.ajax({  
                        url : 'userinfo?code=' + info.code + '&corpid='     //请求后台通过code值获得userId  
                                + _config.corpId,  
                        type : 'GET',  
                        success : function(data, status, xhr) {  
                            var info = JSON.parse(data);  
  
                            document.getElementById("userName").innerHTML = info.name;  
                            document.getElementById("userId").innerHTML = info.userid;  
  
                        },  
                        error : function(xhr, errorType, error) {  
                            logger.e("yinyien:" + _config.corpId);  
                            alert(errorType + ', ' + error);  
                        }  
                    });  
  
                },  
                onFail : function(err) {  
                    alert('fail: ' + JSON.stringify(err));  
                }  
            });  
        });  
  
        dd.error(function(err) {                                             //验证失败  
            alert("进入到error中");  
            document.getElementById("userName").innerHTML = "验证出错";  
            alert('dd error: ' + JSON.stringify(err));  
        });  
    </script>


后台:

public partial class Enterprise_JsAPI : System.Web.UI.Page
{
    public string agentId = string.Empty;
    public string corpId = string.Empty;
    public string timestamp = string.Empty;
    public string nonceStr = string.Empty;
    public string signature = string.Empty;


    protected void Page_Load(object sender, EventArgs e)
    {
        //this.GetConfig();
    }


    public string GetConfig()
    {
        agentId = Config.EAgentID;
        corpId = Config.ECorpId;
        string corpSecret = Config.ECorpSecret;
        nonceStr = Helper.randNonce();
        timestamp = Helper.timeStamp();
        string url = Request.Url.ToString();


        //这里重新实现
        string accessToken = EnterpriseBusiness.GetToken(corpId,corpSecret).access_token;
        string ticket = EnterpriseBusiness.GetTickets(accessToken);
        string string1 = "ticket={0}&nonceStr={1}&timeStamp={2}&url={3}";
        string1 = string.Format(string1, ticket, nonceStr, timestamp, url);
        string signature = FormsAuthentication.HashPasswordForStoringInConfigFile(string1, "SHA1").ToLower();
        return "{jsticket:'" + ticket + "',signature:'" + signature + "',nonceStr:'" + nonceStr + "',timeStamp:'"
    + timestamp + "',corpId:'" + corpId + "',agentId:'" + agentId + "'}";  
    }


}

展开
收起
0天狮座0 2017-04-07 16:49:46 6102 0
3 条回答
写回答
取消 提交回答
  • Re请求后台取不到code值获得userId有问题,一直验证失败(.NET)
    using System;
    using System.Security.Cryptography;
    using System.Text;

    namespace DingTalkApp.Services
    {
        public class DingTalkEncrypt
        {
            public static string GetSwcSH1(string value)
            {
                SHA1 algorithm = SHA1.Create();
                byte[] data = algorithm.ComputeHash(Encoding.UTF8.GetBytes(value));
                string sh1 = "";
                for (int i = 0; i < data.Length; i++)
                {
                    sh1 += data.ToString("x2").ToUpperInvariant();
                }
                return sh1;
            }
            /// <summary>
            /// 创建随机字符串
            /// </summary>
            /// <returns></returns>
            public static string createNonceStr()
            {
                int length = 16;
                string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                string str = "";
                Random rad = new Random();
                for (int i = 0; i < length; i++)
                {
                    str += chars.Substring(rad.Next(0, chars.Length - 1), 1);
                }
                return str;
            }

            /// 将c# DateTime时间格式转换为Unix时间戳格式  
            /// <summary>  
            /// 将c# DateTime时间格式转换为Unix时间戳格式  
            /// </summary>  
            /// <param name="time">时间</param>  
            /// <returns>double</returns>  
            public static int ConvertDateTimeInt(System.DateTime time)
            {
                int intResult = 0;
                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
                intResult = Convert.ToInt32((time - startTime).TotalSeconds);
                return intResult;
            }
        }
    }

    使用时如下
            [HttpGet]
            public System.Collections.IEnumerable GetDtConfig(string userid, string corpid)
            {
                if (!string.IsNullOrEmpty(corpid) && _context.DT_CorpTbs.Where(p => p.CorpID == corpid).Count() > 0)
                {

                    try
                    {
                        string jsurl;
                        var corptbid = _context.DT_CorpTbs.Where(p => p.CorpID == corpid).First();
                        DT_AppTb da = _context.DT_AppTbs.Where(p => p.DT_CorpTbCorpID == corpid).First();

                        jsurl = da.Url;



                        int timestamp = Services.DingTalkEncrypt.ConvertDateTimeInt(DateTime.Now);
                        string nonceStr = Services.DingTalkEncrypt.createNonceStr();
                        string[] paramArr = new String[] { "jsapi_ticket=" + _context.DT_TicketTbs.Where(p => p.DT_TokenTb.DT_CorpTbCorpID == corpid).Select(p => p.ticket).First(), "timestamp=" + timestamp, "noncestr=" + nonceStr, "url=" + jsurl };
                        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
                        Array.Sort(paramArr);
                        // 将排序后的结果拼接成一个字符串
                        string content = string.Concat(paramArr[0], "&", paramArr[1], "&", paramArr[2], "&", paramArr[3]);

                        string signature = Services.DingTalkEncrypt.GetSwcSH1(content).ToLower();

                        ViewData["access_token"] = _context.DT_TokenTbs.Where(p => p.DT_CorpTbCorpID == corpid).Select(p => p.access_token).First();
                        ViewData["agentId"] = da.AgentID;
                        ViewData["corpId"] = corptbid.CorpID;
                        ViewData["timeStamp"] = timestamp;
                        ViewData["nonceStr"] = nonceStr;
                        ViewData["signature"] = signature;
                        ViewData["corpName"] = corptbid.CorpName;
                        ViewData["url"] = da.Url;
                        ViewData["dd_nav_bgcolor"] = da.Dd_nav_bgcolor;
                        return ViewData;

                    }
                    catch
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }

            }


    2017-06-12 11:20:52
    赞同 展开评论 打赏
  • js代码没看出来有错,主要是确认一下corpId,有没有传空,是不是他企业的corpId。

    -------------------------

    回 4楼(0天狮座0) 的帖子
    免登获取code不需要配置dd config 权限校验,这是两个问题了,你的js-api权限校验失败,具体查一下签名的步骤。
    2017-04-10 11:42:11
    赞同 展开评论 打赏
  • Re请求后台取不到code值获得userId有问题,一直验证失败(.NET)
    希望可以得到快速解答

    -------------------------

    Re请求后台取不到code值获得userId有问题,一直验证失败(.NET)
    过去了三天还是没人解答

    -------------------------

    回 3楼象尘的帖子

    -------------------------

    回 3楼象尘的帖子

    -------------------------

    回 3楼象尘的帖子
    后台配置前台展现的图片已经回复你了,cropID是正确的。

    -------------------------

    回 3楼象尘的帖子
    2017-04-07 16:58:06
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载