记住用户名密码
在初学微信开发的时候因为没有经验,再加上微信的官方文档不够清晰,致使看完文档以后只剩下”抓瞎“,根本不知道微信开发是怎样一个流程,也不知道如何开始,因而不得不去查阅第三方博客。
后来终于完成了微信公众号和服务器的对接,实现了网页受权,而且,用户能够直接点击公众号下方的按钮,自动获取OpenID登陆,不用再进行传统的手动登陆了。网页受权自动登陆,也就是本文须要实现的功能。
<?phpnamespace app\index\controller;use app\index\controller\WxController;use app\index\controller\StudentController;use app\index\controller\LoginController;use app\index\model\Student;use app\index\model\Teacher;use app\index\model\Term; class WxindexController extends WxController { public static $openIdTest = 'openIdTest'; public static $page = 'page'; public static $score = 'score'; public static $course = 'course'; public static $info = 'info'; public function page(){ // 跳转到主页 $this->weChatAccredit($this::$page); } public function course(){ // 跳转到课程查询 $this->weChatAccredit($this::$course); } public function score(){ // 跳转到成绩查询 $this->weChatAccredit($this::$score); } public function info(){ // 跳转到我的信息 $this->weChatAccredit($this::$info); } /** * 微信按钮跳转受权 */ public function weChatAccredit($buttonType) { $url = 'http://'.$_SERVER['HTTP_HOST'].'/index/WxIndex/getChatInfo'; $we_chat = new WxController(); //实例化类 $we_chat->accredit($url,$buttonType); //调用方法 } /** * 获取微信用户信息 */ public function getChatInfo(){ $we_chat = new WxController();//实例化微信类 $code = $_GET['code']; //获取跳转后的code $state = $_GET['state']; //获取state $access_token = $we_chat->getAccessToken($code); //根据code获取token $this->gogogo($state,$access_token["openid"]); } //用于跳转到各个方法,传入OpenId和要跳转的方法 public function gogogo($state,$openid) { Student::login($openid); return 'success'; //跳转内容请根据实际状况本身编写 } }
<?php namespace app\index\controller; use think\Controller; class WxController extends Controller{ protected $appid='xxxxxxx'; //你的微信公众号appid protected $appsecret = 'xxxxxxxx'; //你的微信公众号secret //拼接URL public function accredit($redirect_url,$state){ $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirect_url}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect"; $this->redirect($url); } /** * @param $code * @return bool|string */ public function getAccessToken($code){ $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code"; $res = file_get_contents($url); //获取文件内容或获取网络请求的内容 $access_token = json_decode($res,true); return $access_token; } /** * 获取用户信息 * @param unknown $openid * @param unknown $access_token * @return unknown */ public function getWeChatUserInfo($access_token,$openid){ $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$openid}&lang=zh_CN"; $output = file_get_contents($url); $weChatUserInfo = json_decode($output,true); return $weChatUserInfo; } }
目前有 0 条留言 其中:访客:0 条, 博主:0 条