// +---------------------------------------------------------------------- namespace App\Services; use App\Services\Api\MemberService; use Dotenv\Dotenv; use Laravel\Socialite\Facades\Socialite; use SocialiteProviders\WeixinWeb\Provider; /** * 微信服务管理-服务类 * @author laravel开发员 * @since 2020/11/11 * Class WechatService * @package App\Services */ class WechatService extends BaseService { // 静态对象 protected static $instance = null; public function __construct() { $wxAppid = ConfigService::make()->getConfigByCode('wechat_appid'); $wxAppSecret = ConfigService::make()->getConfigByCode('wechat_appsecret'); // 配置更新 if($wxAppid != env('WEIXIN_APP_ID') || $wxAppSecret != env('WEIXIN_SECRET')){ $env = Dotenv::createArrayBacked(base_path())->load(); $env['WEIXIN_APP_ID'] = $wxAppid; $env['WEIXIN_SECRET'] = $wxAppSecret; $envStr = ''; foreach($env as $k => $v){ $envStr .= $k.'='.$v."\n"; } file_put_contents(base_path().'/.env', $envStr); } } /** * 静态入口 * @return WechatService|static|null */ public static function make() { if (!self::$instance) { self::$instance = new static(); } return self::$instance; } /** * 微信授权登录 * @param array $params * @return mixed */ public function auth($params=[]) { $openid = isset($params['openid'])? $params['openid'] : ''; $referrer = isset($params['invite_code'])? $params['invite_code'] : ''; $accessToken = isset($params['access_token'])? $params['access_token'] : ''; if(empty($openid) || empty($accessToken)){ $this->error = '2016'; return false; } // 获取微信用户信息 $wechatInfo = $this->getUserInfo($openid, $accessToken); RedisService::set("caches:wechat:{$openid}:temp", ['params'=> $params,'user'=>$wechatInfo], 7200); // 注册 $appSources = isset($params['app_sources'])? $params['app_sources'] : ''; $wechatInfo['openid'] = $openid; $wechatInfo['mobile'] = isset($params['mobile'])? trim($params['mobile']) : ''; $wechatInfo['device'] = $appSources=='android'? 2 : 1; $wechatInfo['invite_code'] = $referrer; if(!$result = MemberService::make()->loginByWechat($wechatInfo)){ $this->error = MemberService::make()->getError(); return false; }else{ return $result; } } /** * 微信用户信息 * @param $openid * @param $accessToken * @param false $refresh 是否强制刷新 * @return array|mixed */ public function getUserInfo($openid, $accessToken, $refresh = false) { // 获取授权信息 $cacheKey = "caches:wechat:{$openid}:info_".md5($accessToken); $data = RedisService::get($cacheKey); $info = isset($data['info'])? $data['info'] : []; if($info && !$refresh){ return $info; } try { $driver = Socialite::with('weixin'); $driver->setOpenId($openid); $wechatInfo = $driver->userFromToken($accessToken); if ($wechatInfo) { RedisService::set($cacheKey, ['openid' => $openid, 'access_token' => $accessToken, 'info' => $wechatInfo], rand(3600, 7200)); } return $wechatInfo; }catch (\Exception $exception){ RedisService::set($cacheKey.'_error', ['openid' => $openid, 'access_token' => $accessToken, 'error' => $exception->getMessage()], rand(3600, 7200)); return []; } } }