php-钉钉扫码登录功能

参考文档

钉钉官方文档(扫码登录第三方网站-旧)
钉钉官方文档(扫码登录第三方网站-新)
钉钉官方文档(通过sns临时授权码获取用户信息)
他人文章参考-PHP 钉钉第三方扫码登录全套开发

前置步骤

前置步骤建议参考钉钉官方文档,前置步骤包含微应用的创建、应用的配置,接口权限等。本文章主要说前端页面二维码的生成以及php后端对钉钉接口的调用。

主要实现

生成前端二维码

钉钉提供的扫码登录页面的构建主要有2种方式:

方式一:直接以链接跳转的方式生成二维码。

//将链接复制到浏览器中,打开获得登录二维码
https://oapi.dingtalk.com/connect/qrconnect?appid=SuiteKey 
&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=REDIRECT_URI

url里的参数需要换成第三方Web系统对应的参数。在钉钉用户扫码登录并确认后,会302到你指定的redirect_uri,并向url参数中追加临时授权码code及state两个参数。

需要注意的点:

1、参数redirect_uri=REDIRECT_URI涉及的域名,需和登录配置的回调域名一致,否则会提示无权限访问。
2、如果是企业内部应用,appid则为应用的AppKey;如果是第三方企业应用,appid则为应用的SuiteKey。

方式二:将钉钉的二维码嵌入到自己的网页

主要使用的方式,话不多说,直接上代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>钉钉扫码登录测试</title>
</head>
<body>
<div class="text-center">
    <h1 class="display-4" style="text-align: center;">钉钉扫码登录测试</h1>
    <div id="login_container" style="text-align: center;"></div>
</div>
<script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js"></script>
<script type="text/javascript">
    var url = encodeURIComponent("http://********.com/g/login.php?exert=test");
    document.write(url);
    var obj = DDLogin({
        id: "login_container",
        goto: encodeURIComponent('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=**********&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=' + url), 
        style: "border:none;background-color:#FFFFFF;",
        width: "365",
        height: "400",
    });
    var handleMessage = function (event) {
        var origin = event.origin;
        console.log("loginTmpCode", event.data);
        console.log(origin);
        console.log("origin", event.origin);
        if (origin == "https://login.dingtalk.com") { //判断是否来自ddLogin扫码事件。
            var loginTmpCode = event.data; //拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了
            console.log("loginTmpCode", loginTmpCode);
            window.location.href = 
                "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=**********&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=" + url + "&loginTmpCode=" +
                loginTmpCode;
        }
    };
    if (typeof window.addEventListener != 'undefined') {
        window.addEventListener('message', handleMessage, false);
    } else if (typeof window.attachEvent != 'undefined') {
        window.attachEvent('onmessage', handleMessage);
    }
</script>
</body>
</html>

主要注意的点:
1、var obj中的id对应的是html页面的标签的id,生成的二维码会内嵌到这个标签中间。
2、回调的url地址应该设置的和var url的值一致。
3、可以通过设置obj的width和height属性调节二维码图片的大小。
4、如果你的回调地址包含了附加的额外参数,如示例中的?exert=test。那么url必须使用encodeURIComponen()函数处理,否则你的额外参数将会在扫码跳转之后消失。

用户扫码之后登录之后,会302跳转到goto指定的redirect_uri,并向url参数中追加临时授权码code及state参数。这时候可以通过$_GET(‘code’)获取临时授权码。临时授权码只能使用一次。

通过获取的临时授权码code获取用户信息

代码示例如下:

<?php
	$access_key = '**********'; //应用的AppKey
	$app_secret = '**********'; //应用秘钥
	$code = json_encode(['tmp_auth_code' => $_GET['code']]); //获取临时code
	$time = time() . '000'; //毫秒时间戳
    $urlencode_signature = getSignature($time, $app_secret); //签名
    //地址组装,获取用户信息
    $remote_server = 'https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey='. $access_key .'&timestamp=' . $time . '&signature=' . $urlencode_signature; 
    $json = PostCurlRequest($remote_server, $code);
    var_dump($json);
    /**
     * 个人免登场景签名算法 
     */
    function getSignature($timestamp, $appSecret){
    	// 根据timestamp, appSecret计算签名值
	    $s = hash_hmac('sha256', $timestamp, $appSecret, true);
	    $signature = base64_encode($s);
	    $urlencode_signature = urlencode($signature);
	    return $urlencode_signature;
    }

    /**
     * post 请求
     * @param $remote_server
     * @param $post_string
     * @return bool|string
     */
    function PostCurlRequest($remote_server, $code)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $remote_server);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $code);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
?>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值