下面我们以Thinkphp框架为示例来写一个小程序登录接口,并且通过解密方式获取unionid
/* * 小程序登录API接口代码 */ public function check() { $xcx = Config::get('config_api.xcx_user'); $code = input('code'); $encryptedData = input('encryptedData'); $iv = input('iv'); $referrer = input('user_id',0); $unionId = ''; $unifo = []; $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$xcx['app_id']."&secret=".$xcx['app_secret']."&js_code=".$code."&grant_type=authorization_code"; $content = file_get_contents($url); //如果这里返回不了数据,需要换别的方式 $res = object_array(json_decode($content)); //返回openid,expires_in,session_key if(!isset($res)) return json(['code'=>1,'msg'=>'请求失败','res'=>$res]); if(empty($res['openid'])) return json(['code'=>1,'msg'=>'获取openid错误']); if(empty($res['session_key'])) return json(['code'=>1,'msg'=>'session_key获取失败']); if(empty($res['unionid'])){ $pc = new WXBizDataCrypt($xcx['app_id'], $res['session_key']); $errCode = $pc->decryptData($encryptedData, $iv, $data ); if ($errCode == 0) { $arr = object_array(json_decode($data)); // 返回数据: Array ( [openId] => oGZUI0egBJY1zhBYw2KhdUfwVJJE [nickName] => Band [gender] => 1 [language] => zh_CN [city] => Guangzhou [province] => Guangdong [country] => CN [avatarUrl] => http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0 [unionId] => ocMvos6NjeKLIBqg5Mr9QjxrP1FA [watermark] => Array ( [timestamp] => 1477314187 [appid] => wx4f4bc4dec97d474b ) ) } else { return json(['code'=>2,'msg'=>'获取unionId错误']); } }else{ $unionId = $res['unionid']; } if(!empty($unionId)){ $userInfo = UserModel::where( 'unionid',$unionId )->find(); }else{ return json(['code'=>1,'msg'=>'unionid获取失败']); } if(empty($userInfo)){ //生成用户 $createData['unionid'] = $unionId; $createData['openid_xcx'] = $res['openid']; $createData['referrer'] = $referrer; $createData['last_login_time'] = time(); $createData['last_login_ip'] = time(); $createData['login_count'] = 1; $userObj = UserModel::createUser($createData); }else{ //如果存在更新数据 $updateData['last_login_time'] = time(); $updateData['last_login_ip'] = time(); $updateData['login_count'] = $userInfo['login_count']+1; $userObj = UserModel::where('id',$userInfo['id'])->update($updateData); } return json(['code'=>0,'msg'=>'登录成功','userInfo'=>$userInfo]); }