钉钉扫码登陆第三方网站

一、钉钉开放平台文档参考

https://open.dingtalk.com/document/orgapp-server/tutorial-obtaining-user-personal-information

二、登陆钉钉开发者后台,创建H5微应用

在这里插入图片描述

三、点击第二步创建的H5应用,设置回调域名

在这里插入图片描述

四、添加接口权限

这一步是为了扫码时,能获取到扫码人的信息

在这里插入图片描述

五、 前台代码

<div  id="login_container">
</div>
 <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>
<script>
  $(function () {
      var ding = {
          "appid": "",
          "agentid": "",
          "corpid": "",
          " uri": "",
          "redirect_uri": "",
          "code": "",
          "accesstoken": ""
    };
     //这里的appid是设置H5应用的AppKey
     ding.appid = "12345546";
     //设置重定向地址,重定向地址要与步骤三中的回调地址一致
     ding.redirect_uri = window.document.location.origin + '/admin/login.aspx';
     ding.uri = "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=" + ding.appid + "&response_type=code&scope=snsapi_login&state=bind&redirect_uri=" + ding.redirect_uri;
    //2.2.扫码触发事件
     var obj = DDLogin({
         id: "login_container",
         goto: encodeURIComponent(ding.uri),
         style: "border:none;background-color:#FFFFFF;",
         width: "240",
         height: "300",
     });
     
      //监听钉钉扫码获取loginTmpCode
      var getcode = function (event) {
          var origin = event.origin;
          console.log("origin", event.origin);
          if (origin == "https://login.dingtalk.com") { //判断是否来自ddLogin扫码事件。
              var loginTmpCode = event.data; //拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了
              ding.code = loginTmpCode;
              console.log("获取到code", loginTmpCode);
              window.parent.postMessage(loginTmpCode, '*');
              //1.跳转到主页面,微应用自身截取code比对用户信息
              var redirect_uri_check = "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=" + ding.appid + "&response_type=code&scope=snsapi_login&state=bind&redirect_uri=" + ding.redirect_uri + "&loginTmpCode=";
              console.log("获取到redirect_uri_check", redirect_uri_check);
              window.location.href = redirect_uri_check + loginTmpCode;
          };
      };
      //2.4.钉钉扫码监听
      if (typeof window.addEventListener != 'undefined') {
          window.addEventListener('message', getcode, false);
      } else if (typeof window.attachEvent != 'undefined') {
          window.attachEvent('onmessage', getcode);
      };

  })
</script>

六、后台处理

我用的C# 编写的代码,其中用到了钉钉提供的TopSdk.dll,且需要在web.config中配置DingDing:QrAppId及DingDing:QrAppSecret

  var code = Request.QueryString["code"];
  //通过登陆code获取钉钉用户信息
  public static string getDDUserInfo(string code)
  {
      try
      {
          DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
          OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest();
          req.TmpAuthCode = code;
          req.Validate();
          string qrAppId = ConfigurationManager.AppSettings.Get("DingDing:QrAppId");
          string qrAppSecret = ConfigurationManager.AppSettings.Get("DingDing:QrAppSecret");
          OapiSnsGetuserinfoBycodeResponse response = client.Execute(req, qrAppId, qrAppSecret);
          if (response.Errcode == 0)
          {
              return response.UserInfo.Unionid;
          }
          else
          {
              baseLog.warn("code:"+ code + ",response.Errcode:"+ response.Errcode + ",response.ErrCode:"+ response.ErrCode + "请求用户信息失败" + response.Body);
              return null;
          }
      }
      catch (Exception e)
      {
          baseLog.error("请求用户信息异常msg= " + e.Message + ",stack=" + e.StackTrace);
          return null;
      }

  }
   
   //通过unionid获取用户信息
   public static string getDDUserid(string unionid)
    {
        try
        {
            DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
            OapiUserGetbyunionidRequest req = new OapiUserGetbyunionidRequest();
            req.Unionid = unionid;
            req.Validate();
            //string qrAppId = ConfigurationManager.AppSettings.Get("DingDing:QrAppId");
            //string qrAppSecret = ConfigurationManager.AppSettings.Get("DingDing:QrAppSecret");
            OapiUserGetbyunionidResponse response = client.Execute(req, getAccessToken());
            if (response.Errcode == 0)
            {
                return response.Result.Userid;
            }
            else
            {
                baseLog.warn("通过登陆unionid:" + unionid + ",请求用户信息失败" + response.Body);
                return null;
            }
        }
        catch (Exception e)
        {
            baseLog.error("请求用户信息异常msg= " + e.Message + ",stack=" + e.StackTrace);
            return null;
        }
    }


       /// <summary>
      /// 获取钉钉用户的详细信息
      /// </summary>
      /// <param name="userid"></param>
      /// <returns></returns>
      public static OapiV2UserGetResponse getDDUserDetailInfo(string userid)
      {

          try
          {
              DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
              OapiV2UserGetRequest req = new OapiV2UserGetRequest();
              req.Userid = userid;
              req.Language = "zh_CN";
              OapiV2UserGetResponse response = client.Execute(req,getAccessToken());
              baseLog.info("到这一步就成功了" + response.Body);
              if(response.Errcode == 0)
              {
                  return response;
              }
              else
              {
                  baseLog.warn("通过登陆userid:" + userid + ",请求用户信息失败" + response.Body);
                  return null;
              }
          }
          catch (Exception e)
          {
              baseLog.error("请求用户详细信息异常msg=" + e.Message + ",stack=" + e.StackTrace);
              return null;
          }
      }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用第三方库 `django-weixin-auth` 来实现扫码微信二维码登录功能。下面是实现步骤: 1. 安装 `django-weixin-auth` 库:可以通过执行 `pip install django-weixin-auth` 命令来安装。 2. 在 Django 项目的 settings.py 文件添加 `'weixin_auth'` 到 `INSTALLED_APPS` 列表。 3. 执行数据库迁移命令,以创建相应的数据库表: ``` python manage.py migrate ``` 4. 在项目的 urls.py 文件添加以下 URL 配置: ```python from weixin_auth import views urlpatterns = [ # ... path('weixin/login/', views.weixin_login, name='weixin_login'), path('weixin/callback/', views.weixin_callback, name='weixin_callback'), # ... ] ``` 5. 创建一个视图函数来处理微信登录逻辑,例如: ```python from django.shortcuts import redirect def weixin_login(request): # 生成微信授权登录链接 redirect_uri = request.build_absolute_uri(reverse('weixin_callback')) authorize_url = weixin_auth.get_authorize_url(redirect_uri=redirect_uri) # 重定向到微信授权登录页面 return redirect(authorize_url) ``` 6. 创建一个回调视图函数来处理微信授权成功后的回调,例如: ```python from django.contrib.auth import login def weixin_callback(request): # 获取微信用户的授权信息 code = request.GET.get('code') user_info = weixin_auth.get_user_info(code) # 根据用户信息创建或更新用户 user = create_or_update_user(user_info) # 登录用户 login(request, user) # 重定向到登录后的页面 return redirect('home') ``` 请注意,以上代码仅供参考,并且需要根据你的项目需求进行相应的修改。具体的实现细节可以参考 `django-weixin-auth` 库的文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酷啦啦诶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值