微信开发之网页授权获取用户信息(二)(3)

<?php namespace wechat\controllers\classes; use common\tools\wechat\OauthTool; use common\models\User; use common\tools\EmojiTool; /** * 微信用户基本信息获取 */ class UserinfoClass { /** * 用户授权并获取code * @return string 用户code */ public function getCode($route, $state){ $re = new OauthTool; $request = $re->authorize_addr($route, $state); $code = isset($_GET['code']) ? $_GET['code'] : ''; return [$request,$code]; } /** * 获取用户信息并写入数据库(之后加参数传给code) */ public function info($code) { $re = new OauthTool; //获取access token $access = $re->access_token($code); $token = json_decode($access,true); //header("Content-type: text/html; charset=gbk"); //获取用户信息 if(count($token) != ) { $response = $re->userinfo($token['access_token'], $token['openid']); $user = json_decode($response,true); //用户昵称转换 //$user['nickname'] = EmojiTool::emoji_trans($user['nickname']); if($model = User::findOne(['openid' => $user['openid'] ])) { //用户已存在更新数据 $model->attributes = $user; $model->modify_time = time(); $model->save(false); }else{ //用户不存在写入 $model = new User; $model->attributes = $user; $model->create_time = time(); $model->save(false); } } return isset($model->id) ? $model->id : ''; } }

e. 控制器调用(这里只贴其中一个方法)

/** * 产品列表 * @return object 所有可用产品信息 */ public function actionIndex(){ //判断页面是否自动刷新 if(isset($_GET['state'])) { $refresh = ; }else{ $refresh = ; } //获取用户code $user = new UserinfoClass; $request = $user->getCode('r=store/index', ); //该用户userid $userid = $user->info($request[]); $model = new Product; $list = $model->find()->where(['status' => ])->all(); return $this->render('index',['list' => $list, 'refresh' => $refresh, 'userid' => $userid, 'request' => $request]); }

程序要求用户打开产品列表即获取用户信息并存入数据库,其中设计了几个变量作用如下:

$refresh:判断页面是否刷新,由于首次打开页面未进行oauth验证时才自动请求验证,避免反复刷新,这里用回调的state参数作为判断依据且设state=1(若有特定参数需要可将state赋值为所需值);

$request:即为验证请求地址

f. 视图自动刷新

只需要在视图中添加以下js代码即可

<script type="text/javascript"> //自动请求获取code $(function(){ var refresh = <?= $refresh; ?>; var request = '<?= $request[]; ?>'; if(refresh == ){ console.log(); location = request; } }); </script>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/a33dae39c367c97cbb30b8523e803776.html