WeChat.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace app\controller;
  3. use app\model\Account;use think\App;
  4. use think\facade\Cache;use think\facade\Validate;
  5. class WeChat extends Base {
  6. private $wechat=null;
  7. private $token_time=3600;
  8. protected $isLogin = 0;
  9. public function __construct(App $app)
  10. {
  11. parent::__construct($app);
  12. $wechat_conf=['appid'=>env('WECHAT.APPID'),'appsecret'=>env('WECHAT.APPSECRET')];
  13. $this->wechat=new \Wechat($wechat_conf);
  14. $this->token_time= env('token.expire');
  15. }
  16. public function WebAuth(){
  17. $code =$this->request->only(['code'=>''],'post','trim');
  18. $valid =Validate::rule([
  19. 'code|微信授权Code'=>'require|max:255|min:5',
  20. ]);
  21. if($valid->check($code)==false) $this->error($valid->getError());
  22. $uid =$this->wechat->getAccessTokenByCode($code['code']);
  23. if($uid==false){
  24. $this->error('未获取到用户数据');
  25. }
  26. if(!isset($uid['openid'])|| $uid['openid']=='') $this->error('用户openid 未获取到');
  27. $userinfo = $this->checkOpendId($uid['openid']);
  28. $wxinfo = $this->wechat->getUserInfo($uid['openid']);
  29. $this->success("获取成功",["wxinfo"=>$wxinfo,"userinfo"=>$userinfo,"isLogin"=>$this->isLogin]);
  30. }
  31. //网页端调用jssdk配置config
  32. public function getConfig(){
  33. $url =$this->request->only(['url'=>''],'post','trim');
  34. $valid =Validate::rule(['url|微信授权地址'=>'require|max:255|min:5']);
  35. if($valid->check($url)==false)$this->error($valid->getError());
  36. $baseconfig =$this->wechat->getJsTicket();
  37. if($baseconfig==false){
  38. $this->error('签名获取失败');
  39. }
  40. $baseconfig =$this->wechat->getJsSign($url['url']);
  41. if($baseconfig==false){
  42. $this->error('签名获取失败');
  43. }
  44. $this->success('获取成功',$baseconfig);
  45. }
  46. protected function checkOpendId($openId){
  47. $account =new Account();
  48. $isT = $account->withJoin(["userinfo","accountitem"],"left")
  49. ->where(["openId"=>$openId])
  50. ->findOrEmpty();
  51. if($isT->isEmpty())return [];
  52. $token = makeToken($isT);
  53. $cache = Cache::store('redis')->set("user:info:{$token}", $isT->toArray(), $this->token_time);
  54. if ($cache == false) return [];
  55. $isT['token'] = $token;
  56. $this->isLogin=1;
  57. return $isT;
  58. }
  59. }