$name, 'appid' => $appid, 'time' => time(), 'nostr' => uniqid()]; $data['sign'] = md5("{$data['class']}#{$appid}#{$appkey}#{$data['time']}#{$data['nostr']}"); // 创建远程连接,默认使用 JSON-RPC 方式调用接口 $token = enbase64url(json_encode($data, JSON_UNESCAPED_UNICODE)); $jsonrpc = sysconf('wechat.service_jsonrpc|raw') ?: 'https://open.cuci.cc/plugin-wechat-service/api.client/jsonrpc?token=TOKEN'; return new JsonRpcClient(str_replace('token=TOKEN', "token={$token}", $jsonrpc)); } } /** * 获取当前微信APPID. * @throws Exception */ public static function getAppid(): string { if (static::getType() === 'api') { return sysconf('wechat.appid'); } return sysconf('wechat.thr_appid'); } /** * 获取接口授权模式. * @throws Exception */ public static function getType(): string { $type = strtolower(sysconf('wechat.type')); if (in_array($type, ['api', 'thr'])) { return $type; } throw new Exception('请在后台配置微信对接授权模式'); } /** * 获取公众号配置参数. * @param bool $ispay 获取支付参数 * @throws Exception */ public static function getConfig(bool $ispay = false): array { $config = [ 'appid' => static::getAppid(), 'token' => sysconf('wechat.token'), 'appsecret' => sysconf('wechat.appsecret'), 'encodingaeskey' => sysconf('wechat.encodingaeskey'), 'cache_path' => syspath('runtime/wechat'), ]; return $ispay ? static::withWxpayCert($config) : $config; } /** * 获取小程序配置参数. * @param bool $ispay 获取支付参数 * @throws Exception */ public static function getWxconf(bool $ispay = false): array { $wxapp = sysdata('plugin.wechat.wxapp'); $config = [ 'appid' => $wxapp['appid'] ?? '', 'appsecret' => $wxapp['appkey'] ?? '', 'cache_path' => syspath('runtime/wechat'), ]; return $ispay ? static::withWxpayCert($config) : $config; } /** * 处理支付证书配置. * @throws Exception */ public static function withWxpayCert(array $options): array { // 文本模式主要是为了解决分布式部署 $data = sysdata('plugin.wechat.payment'); if (empty($data['mch_id'])) { throw new Exception('无效的支付配置!'); } $name1 = sprintf('wxpay/%s_%s_cer.pem', $data['mch_id'], md5($data['ssl_cer_text'])); $name2 = sprintf('wxpay/%s_%s_key.pem', $data['mch_id'], md5($data['ssl_key_text'])); $local = LocalStorage::instance(); if ($local->has($name1, true) && $local->has($name2, true)) { $sslCer = $local->path($name1, true); $sslKey = $local->path($name2, true); } else { $sslCer = $local->set($name1, $data['ssl_cer_text'], true)['file']; $sslKey = $local->set($name2, $data['ssl_key_text'], true)['file']; } $options['mch_id'] = $data['mch_id']; $options['mch_key'] = $data['mch_key']; $options['mch_v3_key'] = $data['mch_v3_key']; $options['ssl_cer'] = $sslCer; $options['ssl_key'] = $sslKey; $options['cert_public'] = $sslCer; $options['cert_private'] = $sslKey; $options['mp_cert_serial'] = $data['mch_pay_sid'] ?? ''; $options['mp_cert_content'] = $data['ssl_pay_text'] ?? ''; return $options; } /** * 获取会话名称. */ public static function getSsid(): string { $conf = Library::$sapp->session->getConfig(); $ssid = Library::$sapp->request->get($conf['name'] ?? 'ssid'); return empty($ssid) ? Library::$sapp->session->getId() : $ssid; } /** * 通过网页授权获取粉丝信息. * @param string $source 回跳URL地址 * @param int $isfull 获取资料模式 * @param bool $redirect 是否直接跳转 * @throws InvalidResponseException * @throws LocalCacheException * @throws Exception */ public static function getWebOauthInfo(string $source, int $isfull = 0, bool $redirect = true): array { [$ssid, $appid] = [static::getSsid(), static::getAppid()]; $openid = Library::$sapp->cache->get("{$ssid}_openid"); $userinfo = Library::$sapp->cache->get("{$ssid}_fansinfo"); if ((empty($isfull) && !empty($openid)) || (!empty($isfull) && !empty($openid) && !empty($userinfo))) { empty($userinfo) || FansService::set($userinfo, $appid); return ['openid' => $openid, 'fansinfo' => $userinfo]; } if (static::getType() === 'api') { // 解析 GET 参数 $query = parse_url($source, PHP_URL_QUERY); parse_str(is_string($query) ? $query : '', $params); $getVars = [ 'code' => $params['code'] ?? input('code', ''), 'rcode' => $params['rcode'] ?? input('rcode', ''), 'state' => $params['state'] ?? input('state', ''), ]; $wechat = static::WeChatOauth(); if ($getVars['state'] !== $appid || empty($getVars['code'])) { $params['rcode'] = enbase64url($source); $location = strstr("{$source}?", '?', true) . '?' . http_build_query($params); $oauthurl = $wechat->getOauthRedirect($location, $appid, $isfull ? 'snsapi_userinfo' : 'snsapi_base'); throw new HttpResponseException(static::createRedirect($oauthurl, $redirect)); } if (($token = $wechat->getOauthAccessToken($getVars['code'])) && isset($token['openid'])) { $openid = $token['openid']; // 如果是虚拟账号,不保存会话信息,下次重新授权 if (empty($token['is_snapshotuser'])) { Library::$sapp->cache->set("{$ssid}_openid", $openid, 3600); } if ($isfull && isset($token['access_token'])) { $userinfo = $wechat->getUserInfo($token['access_token'], $openid); // 如果是虚拟账号,不保存会话信息,下次重新授权 if (empty($token['is_snapshotuser'])) { $userinfo['is_snapshotuser'] = 0; // 缓存用户信息 Library::$sapp->cache->set("{$ssid}_fansinfo", $userinfo, 3600); empty($userinfo) || FansService::set($userinfo, $appid); } else { $userinfo['is_snapshotuser'] = 1; } } } if ($getVars['rcode']) { throw new HttpResponseException(static::createRedirect(debase64url($getVars['rcode']), $redirect)); } if ((empty($isfull) && !empty($openid)) || (!empty($isfull) && !empty($openid) && !empty($userinfo))) { return ['openid' => $openid, 'fansinfo' => $userinfo]; } throw new Exception('Query params [rcode] not find.'); } else { $result = static::ThinkServiceConfig()->oauth(self::getSsid(), $source, $isfull); [$openid, $userinfo] = [$result['openid'] ?? '', $result['fans'] ?? []]; // 如果是虚拟账号,不保存会话信息,下次重新授权 if (empty($result['token']['is_snapshotuser'])) { Library::$sapp->cache->set("{$ssid}_openid", $openid, 3600); Library::$sapp->cache->set("{$ssid}_fansinfo", $userinfo, 3600); } if ((empty($isfull) && !empty($openid)) || (!empty($isfull) && !empty($openid) && !empty($userinfo))) { empty($result['token']['is_snapshotuser']) && empty($userinfo) || FansService::set($userinfo, $appid); return ['openid' => $openid, 'fansinfo' => $userinfo]; } throw new HttpResponseException(static::createRedirect($result['url'], $redirect)); } } /** * 获取微信网页JSSDK签名参数. * @param null|string $location 签名地址 * @throws InvalidResponseException * @throws LocalCacheException * @throws Exception */ public static function getWebJssdkSign(?string $location = null): array { $location = $location ?: Library::$sapp->request->url(true); if (static::getType() === 'api') { return static::WeChatScript()->getJsSign($location); } return static::ThinkServiceConfig()->jsSign($location); } /** * 解析调用对象名称. */ private static function parseName(string $name): array { foreach (['WeChat', 'WeMini', 'WeOpen', 'WePayV3', 'WePay', 'ThinkService'] as $type) { if (strpos($name, $type) === 0) { [, $base] = explode($type, $name); return [$type, $base, "\\{$type}\\{$base}"]; } } return ['-', '-', $name]; } /** * 网页授权链接跳转. * @param string $location 跳转链接 * @param bool $redirect 强制跳转 */ private static function createRedirect(string $location, bool $redirect = true): Response { return $redirect ? redirect($location) : response(join(";\n", [ sprintf("sessionStorage.setItem('wechat.session','%s')", self::getSsid()), sprintf("location.replace('%s')", $location), '', ])); } }