抖音小程 服务端OpenAPI 开发示例
短信预约 -IT技能 免费直播动态提醒
开发流程如下图
为方便开发 我用的是沙盒模式
开放平台前三个接口开发流程如下,我的代码没做相关优化
代码如下
1、 接口调用凭证
//接口调用凭证 public function getAccessToken() { $uri = 'https://open-sandbox.douyin.com/api/apps/v2/token'; $options = [ 'body' => json_encode([ 'appid' => 'tt5d842b39c2bb31', 'secret' => '9208a4e3130eb24cf9fcbc4a4906765c1', 'grant_type' => 'client_credential']), 'headers' => [ 'Content-Type' => 'application/json' ] ]; $response = (new \GuzzleHttp\Client)->post($uri, $options); $body = $response->getBody(); $stringBody = (string)$body; $result = json_decode($stringBody, true); if ($result['err_no'] == 0) { return $result['data']['access_token']; } return null; }
2、登录 (通过小程序login接口获取到登录凭证后,开发者可以通过服务器发送请求的方式获取 session_key 和 openId)。
//通过小程序login接口获取到登录凭证后,开发者可以通过服务器发送请求的方式获取 session_key 和 openId。 public function code2Session() { $uri = 'https://open-sandbox.douyin.com/api/apps/v2/jscode2session'; //客户端获取并传过来 $code = 'T9loKB1gsyl92x5s7wiTwKteJgeA5Pjq21JNWPtXfx1BUXz0PIzl2ruw2fnPjc9VDA97LlXkKvQW6qTM-0jUNN-frfnVZ5nBluYdVos3FJw8mGe0iaHJHkXq7i4'; $options = [ 'body' => json_encode([ 'appid' => 'tt5d842b39c2b6', 'secret' => '9208a4e3130eb2408fcf9fcbc4a496', 'code' => $code]), 'headers' => [ 'Content-Type' => 'application/json' ] ]; $response = (new \GuzzleHttp\Client)->post($uri, $options); $body = $response->getBody(); $stringBody = (string)$body; $result = json_decode($stringBody, true); if ($result['err_no'] == 0) { return $result['data']; } return ['openid' => '_000DO0RDLCqmW1_EcB4GXidO-bl8T', 'session_key' => '']; }
3、数据缓存
//数据缓存public function setUserstorage() { $user = $this->code2Session(); $body = [ 'kv_list' => [ ['key' => 'name', 'value' => 'yang'] ] ]; //用户登录态签名 $signature = hash_hmac('sha256', json_encode($body), $user['session_key']); $uri = 'https://open-sandbox.douyin.com/api/apps/set_user_storage'; $response = (new \GuzzleHttp\Client)->post($uri, [ 'query' => [ 'access_token' => $this->getAccessToken(), 'openid' => $user['openid'], 'signature' => $signature, 'sig_method' => 'hmac_sha256', ], 'body' => json_encode($body), 'headers' => [ 'Content-Type' => 'application/json' ] ]); $body = $response->getBody(); $stringBody = (string)$body; $result = json_decode($stringBody, true); dd($result); }
来源地址:https://blog.csdn.net/qq_41688060/article/details/129797016
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341