123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166 |
- <?php
- namespace addons\weixin\controller;
- use app\common\library\Auth;
- use think\Config;
- use addons\weixin\library\WechatService;
- use app\admin\model\weixin\User as WechatUser;
- use app\admin\model\User;
- use think\Hook;
- use think\Cookie;
- use think\Session;
- /**
- * 微信公众号接口
- */
- class Index extends \think\addons\Controller
- {
- public $auth = null;
- public function _initialize()
- {
- parent::_initialize();
- $this->auth = $auth = Auth::instance();
- //监听注册登录注销的事件
- Hook::add('user_login_successed', function ($user) use ($auth) {
- $expire = input('post.keeplogin') ? 30 * 86400 : 0;
- Cookie::set('uid', $user->id, $expire);
- Cookie::set('token', $auth->getToken(), $expire);
- });
- }
- /**
- * 微信公众号授权登录和jssdk分享演示
- * http://你的域名/addons/weixin
- */
- public function index()
- {
- //token
- $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
- //初始化
- $this->auth->init($token);
- //检测是否登录
- if (!$this->auth->isLogin()) {
- $this->login();
- }
- return $this->fetch();
- }
- /**
- * 微信公众号服务
- * http://你的域名/addons/weixin/index/serve
- */
- public function serve()
- {
- ob_clean();
- return WechatService::serve();
- }
- /**
- * jssdk配置信息获取
- * http://你的域名/addons/weixin/index/config
- */
- public function config()
- {
- $wxModel = new \app\admin\model\weixin\Config();
- $wxConfigData = $wxModel->where([
- 'group' => 'weixin', 'name' => ['in', 'share_title,share_img,share_synopsis,avatar']
- ])->select();
- $wxConfig = [];
- foreach ($wxConfigData as $val) {
- $wxConfig[$val['name']] = $val['value'];
- }
- $jsSdk = WechatService::jsSdk(urldecode($this->request->post('url')));
- return json(['code' => 1, 'data' => array_merge($wxConfig, $jsSdk)]);
- }
- /*
- * 微信公众号发起授权
- * http://你的域名/addons/weixin/index/login
- * */
- public function login()
- {
- $wechat_data = \app\admin\model\weixin\Config::where(['group' => 'weixin'])->select();
- foreach ($wechat_data as $k => $v) {
- $value = $v->toArray();
- if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
- $value['value'] = explode(',', $value['value']);
- }
- if ($value['type'] == 'array') {
- $value['value'] = (array)json_decode($value['value'], true);
- }
- $wechat[$value['name']] = $value['value'];
- }
- $return_url = "http://" . $_SERVER['HTTP_HOST'] . "/addons/weixin/index/auth";
- $redirect_uri = urlencode($return_url);
- $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$wechat['appid']}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
- header('location:' . $url);
- exit();
- }
- /**
- * 公众号授权回调登陆
- * http://你的域名/addons/weixin/index/auth
- */
- public function auth()
- {
- header('Content-Type: text/html;charset=utf-8');
- header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
- header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
- header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
- header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin');
- $code = $this->request->param('code');
- $tempcodeModel = new \app\common\model\TempCode();
- $openid = $tempcodeModel->where(["code"=>$code])->value("openid");
- if(!$openid) {
- $wxModel = new \app\admin\model\weixin\Config();
- $wxConfigData = $wxModel->where([
- 'group' => 'weixin', 'name' => ['in', 'appid,appsecret']
- ])->select();
- $wxConfig = [];
- foreach ($wxConfigData as $val) {
- $wxConfig[$val['name']] = $val['value'];
- }
- $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$wxConfig['appid']."&secret=".$wxConfig['appsecret']."&code=$code&grant_type=authorization_code";
- $oauth2 = $this->getJson($oauth2Url);
- // 获得 access_token 和openid
- $access_token = $oauth2["access_token"];
- $openid = $oauth2['openid'];
- $tempcodeModel->where(["openid"=>$openid])->delete();
- $tempcodeModel->insert(["code"=>$code,"openid"=>$openid,"create_time"=>time()]);
- }
- $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
- try {
- $wechatInfo = $this->getJson($get_user_info_url);
- } catch (\Exception $e) {
- $this->error('授权失败', '', ['message' => $e->getMessage(), 'line' => $e->getLine()]);
- }
- //授权成功后
- $uid = WechatUser::onWechatOauthAfter($wechatInfo, 0, 0);
- //登录
- $ret = $this->auth->direct($uid);
- if ($ret) {
- $this->success('授权登录成功', url('addons/weixin/index'));
- } else {
- $this->error($this->auth->getError());
- }
- }
- private function getJson($url){
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- $output = curl_exec($ch);
- curl_close($ch);
- return json_decode($output, true);
- }
- }
|