一、需要用户主动点击 button 组件后才能发起获取,获取到的是加密的字符串。
二、获取加密数据成功后,开发者可以把该数据传回到自己的服务端进行解码获。
三、解码数据
具体流程如下
1、小程序 button 按钮 代码片段
2、先点击登录 再 获取登录后的数据
3、服务端解密代码如下
public function get_mobile()
{
$code = "8ExoR0_iWTjHeNwnaGM6QpgzH0wujlm327kV-9ZhVdNLL7If4VDzg7QKIaIF0bnEvauDgvntNMyhdRMvSD0pSYUN3AzYm6ZHp2XF-w";
$iv = "KFJbiztTo/XaS6uPtUKUrQ==";
$encryptedData = "RmCYwmcLFXk9VVBqj6/ENucFAQbzuGTQnIj3MnrN0FQAAKDxYSGFBSZbcq9KfZNBGsIZy3xWeGCMzgH/RPvCEZauHnJvRFZ2pi/0LYO1U6GL182GLelLs3Zz1dH4odFGYA9AHAZcYiIPRZmQK1IQROwuxA6s/Cj+pTixVXyXQaq+iSa1zc51uUwJbEz0P9JhfxQKFeYVn3fTy7c1cMyStQ==";
$session = $this->code2Session($code);
$phone = openssl_decrypt(base64_decode($encryptedData, true), 'AES-128-CBC', base64_decode($session['session_key']), OPENSSL_RAW_DATA, base64_decode($iv));
if ($phone) {
$data = json_decode($phone, true);
return ['code' => 200, 'msg' => '成功', 'data' => $data];
} else {
return ['code' => 201, 'msg' => '失败', 'data' => []];
}
}
public function code2Session($code)
{
$uri = 'https://open-sandbox.douyin.com/api/apps/v2/jscode2session';
$options = [
'body' => json_encode([
'appid' => 'tt5db39c2bb****',
'secret' => '9208a30eb24fcbc4a4906******',
'code' => $code]),
'headers' => [
'Content-Type' => 'application/json'
]
];
$response = (new \GuzzleHttp\Client)->post($uri, $options);
$stringBody = (string)$response->getBody();
$result = json_decode($stringBody, true);
if ($result['err_no'] === 0) {
return $result['data'];
}
return ['openid' => '_000DO0RDLCqmT', 'session_key' => ''];
}