抖音小程序一键获取手机号
/**
* 获取抖音小程序手机号
* @param $code
* @param $iv
* @param $encryptedData
* @return \think\response\Json
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function get_mobile($code, $iv, $encryptedData)
{
$result = $this->code2Session($code);
//解密
$phone = openssl_decrypt(base64_decode($encryptedData, true), 'AES-128-CBC', base64_decode($result['session_key']), OPENSSL_RAW_DATA, base64_decode($iv));
$phone = json_decode($phone, 1);
if (isset($phone['phoneNumber']) && $phone['phoneNumber']) {
return json([
'code' => 1,
'msg' => '获取成功',
'data' => [
'phone' => $phone['phoneNumber']
],
]);
} else {
return json([
'code' => 0,
'msg' => '获取失败',
'data' => [
],
]);
}
}
/**
* 通过code换取 session_key
* @param $code
* @return array
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function code2Session($code)
{
$uri = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
$options = [
'body' => json_encode([
'appid' => config('xinghuo_mp.appid'),
'secret' => config('xinghuo_mp.appsecret'),
'code' => $code,
'anonymous_code' => ''
]),
'headers' => [
'Content-Type' => 'application/json'
]
];
$response = (new \GuzzleHttp\Client)->post($uri, $options);
$stringBody = (string)$response->getBody();
$result = json_decode($stringBody, true);
return ['openid' => $result['data']['openid'], 'session_key' => $result['data']['session_key']];
}