通过官方文档可以更系统的学习到所有的接口,我这边罗列一下我自己用到测试过的接口供大家参考。

  1. 前端-小程序对接官方文档:https://microapp.bytedance.com/docs/zh-CN/mini-app/develop/api/open-interface/user-information/tt-get-user-info
  2. 服务端-小程序官方文档:https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/server-api-introduction

抖音小程序实践三:接口开发指南

1.前端-获取用户信息授权

API文档:https://microapp.bytedance.com/docs/zh-CN/mini-app/develop/api/open-interface/user-information/tt-get-user-info

// tt.getUserProfile(); 获取用户的基本信息,只可在 tap和支付 事件回调中调用,每次调用都会弹出授权提示窗,若用户同意,则会返回用户的真实数据。
    //获取已登录用户的基本信息或特殊信息,首次使用的用户会弹出授权提示窗,若用户同意,则会返回用户的真实数据。
    tt.getUserInfo({
      success(res) {
        console.log("getUserInfo 调用成功", JSON.stringify(res));
      },
      fail(res) {
        console.log("getUserInfo 调用失败", JSON.stringify(res));
      },
     })

响应:

{
    "userInfo": {
        "nickName": "claxxxxxhen",
        "avatarUrl": "https://p9-passport.byteacctimg.com/img/mosaic-legacy/3796/2975xxx00.image",
        "gender": 0,
        "city": "",
        "province": "",
        "country": "",
        "language": "",
        "userId": "37431xxxxx1486",
        "sessionId": "3b652xxxxxxc3b490351ef1311"
    },
    "rawData": "{\"nickName\":\"claixxxxn\",\"avatarUrl\":\"https://p9-passport.byteacctimg.com/img/mosaic-legacy/3796/297xxxx.image\",\"gender\":0,\"city\":\"\",\"province\":\"\",\"country\":\"\",\"language\":\"\"}",
    "signature": "5fed6c636f3cdxxxxx3d2e97e0869d0",
    "encryptedData": "G+kEtB+JE2S3/r8V0Ftxxxx/CxxxxxxxxxxxxxFKKLp6LNpm3QtoHlj2BZREiN8zSE8z7gK51ECsKFDyPn4mtuthY90zj+Zwx0EPyC+DwP1ZJ4ahVawzVkMdnBMhnT48+7CZvOAWa/LyY93MmSsDNLDR0BBTpBnYbnqSW3tGNvTcllNuX2F1Laso2RtsFQlQPoVvoBysfIxliFDvL2+Rw/ZEIc2i7uXnbDeTzPuiiC8km7a/ImZSEZiTdsGNDKEnepmYStswydENgG51NiPRwj15JyOAeALb34xhgYFFZGZFw703XGUbXIn8s8tbqJ+u72cjbqxTp/D7qBL2cHA3uJC6rhrM/VgH7hiDMlwApdRQuFcNQSItQ41RhcD14R7iFoQObc4/IPT0BmvG+WuKMV+PuEp8vaA==",
    "iv": "ar8P0OkTQxxxxqHrW9w==",
    "errMsg": "getUserProfile:ok"
}

Q:此外,什么是用户的openId?什么是用户的unionId?
A:开发者可通过OpenID来获取用户基本信息。特别需要注意的是,如果开发者拥有多个移动应用、网站应用和公众帐号,可通过获取用户基本信息中的unionid来区分用户的唯一性。也就是说,小程序内openId是唯一的,全平台unionId是唯一的。

2.前端-用户登录

API文档:https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/api/open-interface/log-in/tt-login

tt.login({
  force: true,
  success(res) {
    console.log(`login 调用成功${res.code}${res.anonymousCode}`);
  },
  fail(res) {
    console.log(`login 调用失败`);
  },
});

响应:

{
  "anonymousCode": "UAx9YfgVDsxxxxxxxxxxiZCXh7OaAfiW8ei…6mhQP1ETXRfFRKxidnPqMxZtxgXv7yrbWjkBwVePN6FIJq-1Q",
  "code": "1ujmWYVW0mlU4xzzzzzzxxxxxxxxMUkdf9Vp1…g9z0Gy8LFbNekfVjY-Ng6V4_Bc6HxAPQ-SQvrPS8Gf-1ZFvaE",
  "isLogin": true,
  "errMsg": "login:ok"
}

tt.login调用douyin接口登录,获取code/anonymous_code,这两个字段是后续个人加密信息解密的重要字段

3.服务端-jscode2session换取sessionKey

API文档:https://microapp.bytedance.com/docs/zh-CN/mini-app/develop/server/log-in/code-2-session/

        Map<String, String> dataMap = new HashMap<>();
        dataMap.put("appid", "tt60d416xxxxc8801");
        dataMap.put("secret", "582830exxxxc99e14c0999a");
        dataMap.put("code", "3muFdjQoIFZw0WcBLhltspBxxxxxNfT6mkCQO4RbKicdR0j7a12-PRO6yRCHn90HYDg8DerKt_lxoVr1Donbw");
        dataMap.put("anonymous_code", "i8MsKM6tGuKzjxMH3vJF3R4NxAN6xxxxxxxx38wsHAcfmY4dXwaWInvy6isFJ5X8ejQzKcYJVgiPCPkBkMwkw4MrRjFY_iVDOcTOY74");
        HttpResult httpResult = HttpClientUtils.doPostJson("https://developer.toutiao.com/api/apps/v2/jscode2session", JSON.toJSONString(dataMap));//注意这是生产的地址
        String res = httpResult.getBody();
        System.out.println(res);

响应:

{
  "err_no": 0,
  "err_tips": "success",
  "data": {
    "session_key": "hZy6t19VPjFqm********",
    "openid": "V3WvSshYq9******",
    "anonymous_openid": "",
    "unionid": "f7510d9ab***********"
  }
}

4.服务端-敏感信息解密

API文档:https://microapp.bytedance.com/docs/zh-CN/mini-app/develop/api/open-interface/user-information/sensitive-data-process/
这边测试解密用户信息,此外手机号等encryptData的数据,都可以拿这套流程来解密。
我这边主要写了java后端解密的方法,对于js也可以解密,官方文档有比较多的方法展示。

  Base64.Decoder decoder = Base64.getDecoder();
        byte[] sessionKeyBytes = decoder.decode("Ps2xsxxxxxxxJkA==");
        byte[] ivBytes = decoder.decode("ar8P0OxxxxxxqHrW9w==");
        byte[] encryptedBytes =             decoder.decode("cfOy32OwcBaZv7xxxxxxxxxxxvZQHOjzDABhBOWInm0PNGwzXIBkUIZmto2pjC8VDmZS3v3N27OCb2c5E7DblfSVbcjXHuZN7OPB+zOxDADD7Q==");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec skeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec);
        byte[] ret = cipher.doFinal(encryptedBytes);
        String res = new String(ret);
        System.out.println(res);

5.再看看敏感数据解密流程

  1. tt.login调用douyin接口登录,获取code/anonymous_code
  2. getUserProfile,获取iv、encryptedData
  3. jscode2session 获取session_key (前后端获取均可)
  4. 解密用户信息 (前后端解密均可),注意保存用户信息

这样就能够获取openid\unionid\用户明文信息了

6.前端-获取用户设备信息

tt.getSystemInfo({
     success(res) {
       console.log("getSystemInfo 调用成功", JSON.stringify(res));
     },
     fail(res) {
       console.log("getSystemInfo 调用失败", JSON.stringify(res));
     },
   });

响应:


  "language": "zh_CN",
  "version": "6.6.3",
  "brand": "devtools",
  "fontSizeSetting": 16,
  "platform": "devtools",
  "battery": 100,
  "wifiSignal": 4,
  "appName": "devtools",
  "statusBarHeight": 47,
  "nativeSDKVersion": "10.3.0",
  "model": "iPhone 12",
  "system": "iOS 14",
  "deviceScore": {
    "cpu": 7.905,
    "gpu": 9.0622,
    "memory": 7.0344,
    "overall": 7.9524
  },
  "SDKVersion": "2.68.0",
  "pixelRatio": 3,
  "screenWidth": 390,
  "screenHeight": 844,
  "windowWidth": 390,
  "windowHeight": 844,
  "safeArea": {
    "left": 0,
    "right": 390,
    "top": 47,
    "bottom": 810,
    "width": 390,
    "height": 763
  },
  "SDKUpdateVersion": "2.68.0.3",
  "devicePixelRatio": 3,
  "errMsg": "getSystemInfo:ok"
}

7.前端-获取用户手机号

获取抖音API当前登录状态的手机号,获取前需用户授权,否则无法获取。注意:该能力无法直接使用,需申请白名单

小程序获取手机号授权能力仅适用于以下场景:网络购物、帐号下信息内容同步、票务预订、业务办理、信息查询(如:社保、公积金)、预约等,其他不符合使用规范的申请不予开通,申请可参考: 获取用户手机号开通指南

评级达 B 级,且信用分达到 90 分的企业主体小程序,可以申请获取用户手机号能力

tt.getPhoneNumber({
      success(res) {
        console.log("getPhoneNumber 调用成功", JSON.stringify(res));
      },
      fail(res) {
        console.log("getPhoneNumber 调用失败", JSON.stringify(res));
      },
     })

响应:

{
  "detail": {
    "cloudId": "",
    "encryptedData": "0tJ8EV5kwMq8xxxxxxQmf1KG2yKVJX3pYMgWbnY4SJ0MmWMFHJx1ySIaWIgt09sMCL0vAPmgMQ8Hv6d9NgRksOYDTdO1JEmJMy4VGJpBUKL3qqcOvBIc6ToN3RyUTad6Q==",
    "iv": "ZtZtYvS7gNbGMpyYg500rA==",
    "errMsg": "getPhoneNumber:ok"
  },
  "errMsg": "getPhoneNumber:ok"
}

这个数据就一样解密即可

8.前端-获取用户精准位置信息

用于频繁请求地理位置,实时获取精确位置信息。一般适用于打车、外卖等需要频繁请求获取地理位置的行业。需要申请后可查看。

tt.chooseAddress({
     success(res) {
       console.log("chooseAddress 调用成功", JSON.stringify(res));
     },
     fail(res) {
       console.log("chooseAddress 调用失败", JSON.stringify(res));
     },
    })

只要有接口权限,并且是用户登录授权状态,即可获取
响应:

{
  "longitude": 116.3974,
  "latitude": 39.9092,
  "city": "北京市",
  "speed": 0,
  "accuracy": 65,
  "altitude": 0,
  "verticalAccuracy": 65,
  "horizontalAccuracy": 65,
  "errMsg": "getLocation:ok"
}

9.前端-消息订阅

前端发起用户订阅订单消息通知,用户同意后,即可通过接口发送实时订单消息给用户,提升用户体验

小程序消息订阅能力说明

注意:沙盒内测试仅支持安卓,如绑定的设备是IOS的测试会报错 — {"errMsg":"requestSubscribeMessage:fail not supported by current application","errNo":21502}

 tt.requestSubscribeMessage({
      tmplIds: [], // 需要填入开放平台申请的模版id,支持最多3个同类型模版
      success(res) {
        //订阅成功
        console.log("订阅成功", res);
      },
      fail(error) {
        //订阅失败
        console.log("订阅失败, 错误详情: ", error);
        tt.showToast({
          title: "订阅失败",
          icon: "fail",
        });
      },
      complete(res) {
        //订阅完成
        console.log("tt.requestSubscribeMessage API调用完成: ", res);
      },
    });

如果是安卓设备,请求结果如下:

{
  "MSG137673105551c58exxxxx15858": "accept",
  "itemSettings": {
    "MSG137673105551cxxxxxbf15858": "accept"
  },
  "errMsg": "requestSubscribeMessage:ok"
}

10.服务端-获取AccessToken

AccessToken是接口鉴权凭证
access_token 是小程序的全局唯一调用凭据,开发者调用小程序支付时需要使用 access_token。access_token 的有效期为 2 个小时,需要定时刷新 access_token,重复获取会导致之前一次获取的 access_token 的有效期缩短为 5 分钟。

接口:POST https://developer.toutiao.com/api/apps/v2/token
请求示例:

curl --location --request POST 'https://developer.toutiao.com/api/apps/v2/token' \
--header 'Content-Type: application/json' \
--data-raw '{
  "appid": "ttabc*****",
  "secret": "d428***********",
  "grant_type": "client_credential"
}'

响应:

{
  "err_no": 0,
  "err_tips": "success",
  "data": {
    "access_token": "0801121***********",
    "expires_in": 7200
  }
}

11.服务端-发送订阅消息

请求地址: POST https://developer.toutiao.com/api/apps/subscribe_notification/developer/v1/notify
POSTMAN中的请求示例

curl --location --request POST 'https://developer.toutiao.com/api/apps/subscribe_notification/developer/v1/notify' \
--header 'Content-Type: application/json' \
--data-raw '{
  "access_token": "080112184679zzzz7556f426d33673d3d",
  "app_id": "tt60d4166zzzzzzz8801",
  "tpl_id": "MSG137673105zzzzzz7c84bf15858",
  "open_id": "_000S3uzzzzzzzzAzN_zZb",
  "data": {
    "快递派送": "SF1111111111"
  }
}'

响应:

{
    "err_no": 0,
    "err_tips": ""
}

发表回复