Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money
Requirements:
The current H5 application needs to be embedded in the nail for use
Basic configuration
- Create dingding H5 micro Application (address: Dingding Development Platform -> Application Development -> Enterprise Development -> Create Application)
- Obtain basic application information
- Permission to open
- Configure IP egress and link
- Find login related API documentation:
- Developers.dingtalk.com/document/ap…
Development (only the main wrapper code is shown here)
- Create a project Can according to the official document writing (django API: docs.djangoproject.com/zh-hans/2.0…
- Encapsulate the pin API
The structure is generally shown as follows
Server code:
- Access token
@retry(reraise=True, stop=(stop_after_delay(10) | stop_after_attempt(3)), wait=wait_random(min=1, max=3), retry=retry_if_exception_type()) def get_token(self, *args, **kwargs) -> dict: ": result access_token "" path = 'getToken' params = {" appKey ": self.__appkey, "appsecret": self.__appsecret } response = self.conn.get( path=path, params=params, timeout=5 ) data = response.json() errcode = data.get('errcode', -1) if str(errcode) == "0": result = data.get('access_token', {}) result = result if isinstance(result, str) else "" return result return {}Copy the code
- Obtain personnel information by code
def getuserinfo(self, code: str, *args, **kwargs):
path = "/user/getuserinfo"
params = {
"access_token": self.get_token(),
"code": code
}
response = self.conn.get(
path=path,
params=params,
timeout=5
)
data = response.json()
errcode = data.get('errcode', -1)
if str(errcode) == '0':
result = data
result = result if isinstance(result, dict) else {}
user_id = result.get('userid')
response = self._get_user_detail(user_id)
return response
return {}
Copy the code
- Obtaining Personnel Details
def _get_user_detail(self, user_id: str, *args, **kwargs): key = str(user_id) + "_get_user_detail" info = redisClient.authcache('get', key) if info: return info path = '/topapi/v2/user/get? access_token={}'.format(self.get_token()) params = { "language": "zh_CN", "userid": user_id } response = self.conn.post( path=path, params=params, timeout=5 ) data = response.json() errcode = data.get('errcode', -1) if str(errcode) == '0': result = data.get('result', {}) result = result if isinstance(result, dict) else {} redisClient.authcache('set', key, result) return result return {}Copy the code
The front-end code
- The PC code
< script SRC = "https://g.alicdn.com/dingding/dingtalk-jsapi/2.10.3/dingtalk.open.js" > < / script > < p > Opening with the system default browser(Google Chrome Recommened) ... . < / p > < script > dd. Ready (function () {dd. Runtime. Permission. RequestAuthCode ({corpId: "{{corpId}}", / / enterprise id onSuccess: function (result) { dd.biz.util.openLink({ url: Protocol + "//" + window.location.host + "{{uri}}&code=" + result.code,// The address to open the link onSuccess: function (result) { /**/ }, onFail: function (err) { } }); }, onFail: function (error) {alert(' pin authentication failed! ${JSON.stringify(error)}`); }}); }); </script>Copy the code
- Mob server-side code
< script SRC = "https://g.alicdn.com/dingding/dingtalk-jsapi/2.10.3/dingtalk.open.js" > < / script > < script > dd. Ready (function () {dd. Runtime. Permission. RequestAuthCode ({corpId: "{{corpId}}", / / enterprise id onSuccess: function (result) { dd.biz.navigation.replace({ url: Protocol + "//" + window.location.host + "{{uri}}&code=" + result.code,// The address to open the link onSuccess: function (result) { /**/ }, onFail: function (err) { } }); }, onFail: function (error) {alert(' pin authentication failed! ${JSON.stringify(error)}`); }}); }); </script>Copy the code
- Login completed jump to the home page (session processing here)
<script>
setTimeout(function () {
document.location.resession_dict
document.location.replace("{{ uri }}");
}, 0)
</script>
Copy the code
Scan code login page implementation
<p align="value" style="text-align:center">{{ title }}</p> <div id="login_container" style="text-align:center"></div> < script SRC = "https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js" > < / script > < script > var url = encodeURIComponent('users/login/'); var goto = encodeURIComponent('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid={{ appid }}&response_type=code&scope=snsapi_login&state=test&redirect_uri=' + window.location.protocol + "//" + window.location.host + url) var obj = DDLogin({ id: "Login_container ",// you need to define an HTML tag on your page and set the ID, For example, <div id="login_container"></div> or <span id="login_container"></ SPAN > goto: goto, style: "border:none; background-color:#FFFFFF;" , width: "300", height: "400" }); var hanndleMessage = function (event) { var origin = event.origin; console.log("origin", event.origin); If (origin = = "https://login.dingtalk.com") {/ / determine whether from ddLogin scan code. var loginTmpCode = event.data; Console. log("loginTmpCode", loginTmpCode); var url2 = "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid={{appid}}&response_type=code&scope=snsapi_login&state=NvSx TQh&redirect_uri=" + window.location.protocol + "//" + window.location.host + url + "&loginTmpCode=" + loginTmpCode; console.log("url2", url2) window.location.href = url2; }}; if (typeof window.addEventListener ! = 'undefined') { window.addEventListener('message', hanndleMessage, false); } else if (typeof window.attachEvent ! = 'undefined') { window.attachEvent('onmessage', hanndleMessage); } </script>Copy the code