前端代码组件
<button v-if="!isfromorderlist" class="get-phone-btn" open-type="getphonenumber" @getphonenumber="ongetphonenumber" > 一键获取 </button>
// 获取手机号回调 ongetphonenumber(e) { var that = this tt.login({ force: true, success(res) { console.log('获取手机号回调', e) if (e.detail.errmsg === 'getphonenumber:ok') { // 获取成功,调用后端接口解密手机号 that.decryptphonenumber(res.code,e.detail.iv,e.detail.encrypteddata) } else { uni.showtoast({ title: '获取手机号失败', icon: 'none' }) } }, fail(res) { console.log(`login 调用失败`); }, }); }, // 解密手机号 后端php进行解密 async decryptphonenumber(code,iv,encrypteddata) { try { const res = await orderapi.decryptphone({ code: code, iv: iv, encrypteddata: encrypteddata }) if (res.code === 1 && res.data && res.data.phone) { this.phone = res.data.phone } else { throw new error(res.msg || '获取手机号失败') } } catch (error) { console.error('解密手机号失败:', error) uni.showtoast({ title: error.message || '获取手机号失败', icon: 'none' }) } }
后端使用的php去实现 思路首先通过前端的code换取sessionkey 然后通过 sessionkey解密前端手机号加密信息
/** * 获取抖音小程序手机号 * @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']]; }
到此这篇关于抖音小程序一键获取手机号的实现思路的文章就介绍到这了,更多相关抖音小程序一键获取手机号内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论