Index.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. <?php
  2. namespace addons\weixin\controller;
  3. use app\common\library\Auth;
  4. use think\Config;
  5. use addons\weixin\library\WechatService;
  6. use app\admin\model\weixin\User as WechatUser;
  7. use app\admin\model\User;
  8. use think\Hook;
  9. use think\Cookie;
  10. use think\Session;
  11. /**
  12. * 微信公众号接口
  13. */
  14. class Index extends \think\addons\Controller
  15. {
  16. public $auth = null;
  17. public function _initialize()
  18. {
  19. parent::_initialize();
  20. $this->auth = $auth = Auth::instance();
  21. //监听注册登录注销的事件
  22. Hook::add('user_login_successed', function ($user) use ($auth) {
  23. $expire = input('post.keeplogin') ? 30 * 86400 : 0;
  24. Cookie::set('uid', $user->id, $expire);
  25. Cookie::set('token', $auth->getToken(), $expire);
  26. });
  27. }
  28. /**
  29. * 微信公众号授权登录和jssdk分享演示
  30. * http://你的域名/addons/weixin
  31. */
  32. public function index()
  33. {
  34. //token
  35. $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
  36. //初始化
  37. $this->auth->init($token);
  38. //检测是否登录
  39. if (!$this->auth->isLogin()) {
  40. $this->login();
  41. }
  42. return $this->fetch();
  43. }
  44. /**
  45. * 微信公众号服务
  46. * http://你的域名/addons/weixin/index/serve
  47. */
  48. public function serve()
  49. {
  50. ob_clean();
  51. return WechatService::serve();
  52. }
  53. /**
  54. * jssdk配置信息获取
  55. * http://你的域名/addons/weixin/index/config
  56. */
  57. public function config()
  58. {
  59. $wxModel = new \app\admin\model\weixin\Config();
  60. $wxConfigData = $wxModel->where([
  61. 'group' => 'weixin', 'name' => ['in', 'share_title,share_img,share_synopsis,avatar']
  62. ])->select();
  63. $wxConfig = [];
  64. foreach ($wxConfigData as $val) {
  65. $wxConfig[$val['name']] = $val['value'];
  66. }
  67. $jsSdk = WechatService::jsSdk(urldecode($this->request->post('url')));
  68. return json(['code' => 1, 'data' => array_merge($wxConfig, $jsSdk)]);
  69. }
  70. /*
  71. * 微信公众号发起授权
  72. * http://你的域名/addons/weixin/index/login
  73. * */
  74. public function login()
  75. {
  76. $wechat_data = \app\admin\model\weixin\Config::where(['group' => 'weixin'])->select();
  77. foreach ($wechat_data as $k => $v) {
  78. $value = $v->toArray();
  79. if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
  80. $value['value'] = explode(',', $value['value']);
  81. }
  82. if ($value['type'] == 'array') {
  83. $value['value'] = (array)json_decode($value['value'], true);
  84. }
  85. $wechat[$value['name']] = $value['value'];
  86. }
  87. $return_url = "http://" . $_SERVER['HTTP_HOST'] . "/addons/weixin/index/auth";
  88. $redirect_uri = urlencode($return_url);
  89. $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";
  90. header('location:' . $url);
  91. exit();
  92. }
  93. /**
  94. * 公众号授权回调登陆
  95. * http://你的域名/addons/weixin/index/auth
  96. */
  97. public function auth()
  98. {
  99. header('Content-Type: text/html;charset=utf-8');
  100. header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
  101. header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
  102. header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
  103. header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin');
  104. $code = $this->request->param('code');
  105. $tempcodeModel = new \app\common\model\TempCode();
  106. $openid = $tempcodeModel->where(["code"=>$code])->value("openid");
  107. if(!$openid) {
  108. $wxModel = new \app\admin\model\weixin\Config();
  109. $wxConfigData = $wxModel->where([
  110. 'group' => 'weixin', 'name' => ['in', 'appid,appsecret']
  111. ])->select();
  112. $wxConfig = [];
  113. foreach ($wxConfigData as $val) {
  114. $wxConfig[$val['name']] = $val['value'];
  115. }
  116. $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$wxConfig['appid']."&secret=".$wxConfig['appsecret']."&code=$code&grant_type=authorization_code";
  117. $oauth2 = $this->getJson($oauth2Url);
  118. // 获得 access_token 和openid
  119. $access_token = $oauth2["access_token"];
  120. $openid = $oauth2['openid'];
  121. $tempcodeModel->where(["openid"=>$openid])->delete();
  122. $tempcodeModel->insert(["code"=>$code,"openid"=>$openid,"create_time"=>time()]);
  123. }
  124. $get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN";
  125. try {
  126. $wechatInfo = $this->getJson($get_user_info_url);
  127. } catch (\Exception $e) {
  128. $this->error('授权失败', '', ['message' => $e->getMessage(), 'line' => $e->getLine()]);
  129. }
  130. //授权成功后
  131. $uid = WechatUser::onWechatOauthAfter($wechatInfo, 0, 0);
  132. //登录
  133. $ret = $this->auth->direct($uid);
  134. if ($ret) {
  135. $this->success('授权登录成功', url('addons/weixin/index'));
  136. } else {
  137. $this->error($this->auth->getError());
  138. }
  139. }
  140. private function getJson($url){
  141. $ch = curl_init();
  142. curl_setopt($ch, CURLOPT_URL, $url);
  143. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  144. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  145. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  146. $output = curl_exec($ch);
  147. curl_close($ch);
  148. return json_decode($output, true);
  149. }
  150. }