Js.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace app\wechat\controller\api;
  3. use app\wechat\service\WechatService;
  4. use think\admin\Controller;
  5. use think\Response;
  6. /**
  7. * 前端JS获取控制器
  8. * Class Js
  9. * @package app\wechat\controller\api
  10. */
  11. class Js extends Controller
  12. {
  13. /** @var string */
  14. protected $params;
  15. /** @var string */
  16. protected $openid;
  17. /** @var string */
  18. protected $fansinfo;
  19. /**
  20. * 生成网页授权的JS内容
  21. * @return \think\Response
  22. * @throws \WeChat\Exceptions\InvalidResponseException
  23. * @throws \WeChat\Exceptions\LocalCacheException
  24. * @throws \think\admin\Exception
  25. * @throws \think\db\exception\DataNotFoundException
  26. * @throws \think\db\exception\DbException
  27. * @throws \think\db\exception\ModelNotFoundException
  28. */
  29. public function index(): Response
  30. {
  31. $mode = $this->request->get('mode', 1);
  32. $source = $this->request->server('http_referer') ?: $this->request->url(true);
  33. $userinfo = WechatService::instance()->getWebOauthInfo($source, $mode, false);
  34. if (empty($userinfo['openid'])) {
  35. $content = 'alert("Wechat webOauth failed.")';
  36. } else {
  37. $this->openid = $userinfo['openid'];
  38. $this->params = json_encode(WechatService::instance()->getWebJssdkSign($source));
  39. $this->fansinfo = json_encode($userinfo['fansinfo'] ?? [], JSON_UNESCAPED_UNICODE);
  40. // 生成数据授权令牌
  41. $this->token = uniqid('oauth') . rand(10000, 99999);
  42. $this->app->cache->set($this->openid, $this->token, 3600);
  43. // 生成前端JS变量代码
  44. $content = $this->_buildContent();
  45. }
  46. return Response::create($content)->contentType('application/x-javascript');
  47. }
  48. /**
  49. * 给指定地址创建签名参数
  50. * @throws \WeChat\Exceptions\InvalidResponseException
  51. * @throws \WeChat\Exceptions\LocalCacheException
  52. * @throws \think\admin\Exception
  53. * @throws \think\db\exception\DataNotFoundException
  54. * @throws \think\db\exception\DbException
  55. * @throws \think\db\exception\ModelNotFoundException
  56. */
  57. public function sdk()
  58. {
  59. $data = $this->_vali(['url.require' => '签名地址不能为空!']);
  60. $this->success('获取签名参数', WechatService::instance()->getWebJssdkSign($data['url']));
  61. }
  62. /**
  63. * 生成授权内容
  64. * @return string
  65. */
  66. private function _buildContent(): string
  67. {
  68. return <<<EOF
  69. if(typeof wx === 'object'){
  70. wx.token="{$this->token}";
  71. wx.openid="{$this->openid}";
  72. wx.fansinfo={$this->fansinfo};
  73. wx.config({$this->params});
  74. wx.ready(function(){
  75. wx.hideOptionMenu();
  76. wx.hideAllNonBaseMenuItem();
  77. });
  78. }
  79. EOF;
  80. }
  81. }