WechatMp.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 https://www.sapixx.com All rights reserved.
  4. * @license Licensed (http://www.apache.org/licenses/LICENSE-2.0).
  5. * @author pillar<ltmn@qq.com>
  6. * 微信公众号回调处理
  7. */
  8. namespace app\system\controller\event;
  9. use think\Controller;
  10. use app\common\model\SystemMemberMiniapp;
  11. use app\common\model\SystemUser;
  12. use app\common\event\User;
  13. use app\common\facade\WechatMp as Mp;
  14. use encrypter\Encrypter;
  15. use filter\Filter;
  16. use Exception;
  17. class WechatMp extends Controller{
  18. /**
  19. * 发起微信授权
  20. */
  21. public function putWechat(){
  22. try {
  23. $app = $this->request->param('app/d');
  24. $scope = $this->request->param('scope/d',1);
  25. $url = $this->request->param('url');
  26. $official = Mp::isTypes($app);
  27. if(!$official){
  28. $this->error('请先授权您的公众号');
  29. }
  30. $response = $official->oauth->scopes([$scope ? 'snsapi_userinfo' : 'snsapi_base'])->redirect(url('system/event.wechatMp/getWechat',['app' => $app,'url' => $url],true,true));
  31. return $response->send();
  32. }catch (Exception $e) {
  33. $this->error('授权失败');
  34. }
  35. }
  36. /**
  37. * 回调微信授权
  38. */
  39. public function getWechat(){
  40. $app = $this->request->param('app/d');
  41. $code = $this->request->param('code');
  42. $url = $this->request->param('url');
  43. if(empty($code)){
  44. return $this->redirect('system/event.wechatMp/putWechat',['app' => $app,'url' => $url]);
  45. }
  46. //判断是否开放平台应用
  47. $miniapp = SystemMemberMiniapp::where(['id' => $app])->find();
  48. if(!$miniapp){
  49. $this->error('未找到已授权应用');
  50. }
  51. $official = Mp::isTypes($app);
  52. if(!$official){
  53. $this->error('请先授权您的公众号');
  54. }
  55. $rel = $official->oauth->user();
  56. $result = SystemUser::where(['member_miniapp_id' => $miniapp->miniapp_id,'official_uid' => $rel->getID()])->find();
  57. if(empty($result)){
  58. $nickName = Filter::filter_Emoji($rel->getName());
  59. $data['miniapp_id'] = $app;
  60. $data['wechat_uid'] = empty($rel['unionid']) ? '' : $rel['unionid'];
  61. $data['official_uid'] = $rel->getID();
  62. $data['nickname'] = $nickName ?? '微信-'.time();
  63. $data['avatar'] = $rel->getAvatar();
  64. $data['miniapp_uid'] = '';
  65. $data['session_key'] = '';
  66. $uid = SystemUser::wechatReg($data,false);
  67. if(!$uid){
  68. return $this->redirect(Encrypter::cpDecode($url));
  69. }
  70. User::setLogin(['id'=> $uid,'nickname'=>$rel->getName()]);
  71. }else{
  72. User::setLogin($result);
  73. }
  74. return $this->redirect(Encrypter::cpDecode($url));
  75. }
  76. }