123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace app\wechat\controller\api;
- use app\wechat\service\WechatService;
- use think\admin\Controller;
- use think\Response;
- class Js extends Controller
- {
-
- protected $params;
-
- protected $openid;
-
- protected $fansinfo;
-
- public function index(): Response
- {
- $mode = $this->request->get('mode', 1);
- $source = $this->request->server('http_referer') ?: $this->request->url(true);
- $userinfo = WechatService::instance()->getWebOauthInfo($source, $mode, false);
- if (empty($userinfo['openid'])) {
- $content = 'alert("Wechat webOauth failed.")';
- } else {
- $this->openid = $userinfo['openid'];
- $this->params = json_encode(WechatService::instance()->getWebJssdkSign($source));
- $this->fansinfo = json_encode($userinfo['fansinfo'] ?? [], JSON_UNESCAPED_UNICODE);
-
- $this->token = uniqid('oauth') . rand(10000, 99999);
- $this->app->cache->set($this->openid, $this->token, 3600);
-
- $content = $this->_buildContent();
- }
- return Response::create($content)->contentType('application/x-javascript');
- }
-
- public function sdk()
- {
- $data = $this->_vali(['url.require' => '签名地址不能为空!']);
- $this->success('获取签名参数', WechatService::instance()->getWebJssdkSign($data['url']));
- }
-
- private function _buildContent(): string
- {
- return <<<EOF
- if(typeof wx === 'object'){
- wx.token="{$this->token}";
- wx.openid="{$this->openid}";
- wx.fansinfo={$this->fansinfo};
- wx.config({$this->params});
- wx.ready(function(){
- wx.hideOptionMenu();
- wx.hideAllNonBaseMenuItem();
- });
- }
- EOF;
- }
- }
|