| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434 |
- <?php
- namespace App\Services;
- /**
- * 微信服务管理-服务类
- * @author laravel开发员
- * @since 2020/11/11
- * Class WechatService
- * @package App\Services
- */
- class MpService extends BaseService
- {
- // 静态对象
- protected static $instance = null;
- protected $debug = true;
- protected $expireTime = 7200; // 缓存日志时长
- protected $mpAppid = ''; // 小程序APPID
- protected $mpAppSecret = ''; // 小程序密钥
- protected $wechatAppid = ''; // 公众号APPID
- protected $wechatAppSecret = ''; // 公众号密钥
- // 接口地址
- protected $apiUrls = [
- // 小程序授权登录
- 'auth' => 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',
- // 网页版授权
- 'authorize' => 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=%s#wechat_redirect',
- // 获取token
- 'getToken' => 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',
- // 获取二维码
- 'getQrcode' => 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s&scene=%s&page=%s&env_version=%s',
- // 生成小程序分享链接
- 'getSchemeLink'=>'https://api.weixin.qq.com/wxa/generatescheme?access_token=%s',
- // 短链接
- 'getShortLink'=>'https://api.weixin.qq.com/wxa/genwxashortlink?access_token=%s',
- // 获取用户信息
- 'getUserInfo' => 'https://api.weixin.qq.com/sns/jscode2session',
- // 获取公众号accessToken和openid
- 'getWechatAccessToken' => 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code',
- // 公众号用户信息
- 'getWechatUserInfo' => 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN',
- // 获取手机号
- 'getPhoneNumber' => 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s',
- ];
- public function __construct()
- {
- $this->mpAppid = ConfigService::make()->getConfigByCode('wechat_mp_appid');
- $this->mpAppSecret = ConfigService::make()->getConfigByCode('wechat_mp_appsecret');
- $this->wechatAppid = ConfigService::make()->getConfigByCode('wechat_appid');
- $this->wechatAppSecret = ConfigService::make()->getConfigByCode('wechat_app_secret');
- }
- /**
- * 静态入口
- * @return static|null
- */
- public static function make()
- {
- if (!self::$instance) {
- self::$instance = new static();
- }
- return self::$instance;
- }
- /**
- * 获取基础接口 access_token
- * @param false $refresh
- * @return false|mixed|string
- */
- public function getAccessToken($refresh = false, $platform = 'mp')
- {
- try {
- $appId = $this->mpAppid;
- $appSecret = $this->mpAppSecret;
- if ($platform == 'wechat') {
- $appId = $this->wechatAppid;
- $appSecret = $this->wechatAppSecret;
- if (empty($this->wechatAppid) || empty($this->wechatAppSecret)) {
- $this->error = '公众号参数未配置';
- return false;
- }
- } else {
- if (empty($this->mpAppid) || empty($this->mpAppSecret)) {
- $this->error = '小程序参数未配置';
- return false;
- }
- }
- $cacheKey = "caches:mpApp:{$platform}_{$appId}:";
- $tokenData = RedisService::get($cacheKey . 'access_token');
- $token = isset($tokenData['access_token']) ? $tokenData['access_token'] : '';
- if ($token && !$refresh) {
- return $token;
- }
- $url = sprintf($this->apiUrls["getToken"], $appId, $appSecret);
- $result = httpRequest($url, '', 'get', '', 5);
- $this->saveLog($cacheKey . 'tokens:request', ['url' => $url, 'result' => $result, 'date' => date('Y-m-d H:i:s')]);
- $token = isset($result['access_token']) ? $result['access_token'] : '';
- if (empty($result) || empty($token)) {
- $this->error = '获取TOKEN失败';
- return false;
- }
- $result['date'] = date('Y-m-d H:i:s');
- RedisService::set($cacheKey . 'access_token', $result, 7000);
- return $token;
- } catch (\Exception $e) {
- $this->error = $e->getMessage();
- $this->saveLog($cacheKey . 'tokens:error', ['error' => $this->error, 'trace' => $e->getTrace(), 'date' => date('Y-m-d H:i:s')]);
- return false;
- }
- }
- /**
- * 小程序二维码
- * @param $page 页面
- * @param $scene 场景参数
- * @param string $version 类型:release-永久
- * @param false $refresh
- * @return false|string
- */
- public function getMiniQrcode($page, $scene, $version = 'release', $refresh = false)
- {
- if (!in_array($version, ['release', 'trial', 'develop'])) {
- $version = 'release';
- }
- try {
- if (empty($page) || empty($scene)) {
- $this->error = '缺少二维码参数';
- return false;
- }
- if (empty($this->mpAppid) || empty($this->mpAppSecret)) {
- $this->error = '小程序参数未配置';
- return false;
- }
- if (!$token = $this->getAccessToken()) {
- $this->error = '获取token失败';
- return false;
- }
- $cacheKey = "caches:members:mp_{$this->mpAppid}:";
- $filePath = base_path('public/uploads');
- $qrFile = '/qrcodes/mp_' . date("YmdHis") . "_" . md5($page . $scene) . ".png";
- $qrKey = md5(date("Ym") . $page . $scene);
- if (RedisService::get($cacheKey . $qrKey) && file_exists($filePath . '/' . $qrFile) && !$refresh) {
- return $qrFile;
- }
- if (!is_dir($filePath . '/qrcodes/')) {
- @mkdirs($filePath . '/qrcodes/');
- }
- $data = ['page' => $page, 'scene' => $scene, 'check_path' => false, 'env_version' => $version];
- $url = sprintf($this->apiUrls['getQrcode'], $token, $scene, $page, $version);
- $result = curl_post($url, json_encode($data));
- $datas = $result ? json_decode($result, true) : [];
- $this->saveLog($cacheKey . 'qrcode:request', ['page' => $page, 'scene' => $scene, 'url' => $url, 'result' => $result, 'date' => date('Y-m-d H:i:s')]);
- $errcode = isset($datas['errcode']) ? $datas['errcode'] : '';
- $errmsg = isset($datas['errmsg']) ? $datas['errmsg'] : '';
- if ($errcode) {
- $this->error = $errmsg ? $errmsg : '获取二维码失败';
- return false;
- }
- file_put_contents($filePath . '/' . $qrFile, $result);
- if (!file_exists($filePath . '/' . $qrFile)) {
- $this->error = '生成二维码失败';
- return false;
- }
- RedisService::set($cacheKey . $qrKey, ['page' => $page, 'scene' => $scene, 'qrcode' => $qrFile, 'date' => date('Y-m-d H:i:s')], 30 * 86400);
- return $qrFile;
- } catch (\Exception $e) {
- $this->error = $e->getMessage();
- $this->saveLog($cacheKey . 'qrcode:error', ['page' => $page, 'scene' => $scene, 'error' => $this->error, 'trace' => $e->getTrace(), 'date' => date('Y-m-d H:i:s')]);
- return false;
- }
- }
- /**
- * 小程序分享链接
- * @param $path 页面路径
- * @param $query 地址参数
- * @param false $refresh
- * @return false|string
- */
- public function getMiniShareLink($path, $query,$isExpire=false,$linkType=2, $refresh=false)
- {
- try {
- if(empty($path) || empty($query)){
- $this->error = '缺少链接参数';
- return false;
- }
- if(empty($this->mpAppid) || empty($this->mpAppSecret)){
- $this->error = '小程序参数未配置';
- return false;
- }
- if(!$token = $this->getAccessToken())
- {
- $this->error = '获取token失败';
- return false;
- }
- $cacheKey = "caches:members:mpShare_{$this->mpAppid}:{$linkType}_".md5($path.$query);
- $link = RedisService::get($cacheKey);
- if($link && !$refresh){
- return $link;
- }
- if($linkType == 1){
- $data = [
- 'jump_wxa'=>[
- 'path'=>$path,
- 'query'=>$query,
- ],
- 'is_expire'=> $isExpire,
- ];
- }else if($linkType ==2){
- $data=[
- 'page_url'=> $path,
- 'page_title'=> $query,
- 'is_permanent'=>$isExpire
- ];
- }
- $linkTypes = [1=>'getSchemeLink',2=>'getShortLink'];
- $name = isset($linkTypes[$linkType])?$linkTypes[$linkType]: 'getShortLink';
- $url = sprintf($this->apiUrls[$name], $token);
- $result = curl_post($url, json_encode($data));
- $datas = $result? json_decode($result, true) : [];
- $this->saveLog($cacheKey.'_result', ['path'=>$path,'query'=>$query,'linkType'=>$linkType,'url'=>$url,'result'=>$result,'date'=>date('Y-m-d H:i:s')]);
- $errcode = isset($datas['errcode'])? $datas['errcode'] : '';
- $errmsg = isset($datas['errmsg'])? $datas['errmsg'] : '';
- $link =isset($datas['link'])? $datas['link'] : '';
- if($errcode || empty($link)){
- $this->error = $errmsg? $errmsg : '获取链接失败';
- return false;
- }
- RedisService::set($cacheKey,$link, rand(3600,7200));
- return $link;
- }catch (\Exception $e){
- $this->error = $e->getMessage();
- $this->saveLog($cacheKey.'_error', ['path'=>$path,'query'=>$query,'linkType'=>$linkType,'error'=>$this->error,'trace'=>$e->getTrace(),'date'=>date('Y-m-d H:i:s')]);
- return false;
- }
- }
- /**
- * 获取授权信息
- * @param $code
- * @param $platform mp-小程序,wechat-公众号
- * @return array|false|mixed|string[]
- */
- public function getUserinfo($code, $platform = 'mp')
- {
- try {
- if (empty($code)) {
- $this->error = '缺少授权参数';
- return false;
- }
- $appId = $this->mpAppid;
- $appSecret = $this->mpAppSecret;
- $cacheKey = "caches:mpApp:{$platform}_{$appId}:";
- $data = '';
- if ($platform == 'wechat') {
- $appId = $this->wechatAppid;
- $appSecret = $this->wechatAppSecret;
- if (empty($this->wechatAppid) || empty($this->wechatAppSecret)) {
- $this->error = '公众号参数未配置';
- return false;
- }
- $url = sprintf($this->apiUrls['getWechatAccessToken'], $appId, $appSecret, $code);
- } else {
- if (empty($this->mpAppid) || empty($this->mpAppSecret)) {
- $this->error = '小程序参数未配置';
- return false;
- }
- $data = [
- 'appid' => $appId,
- 'secret' => $appSecret,
- 'js_code' => $code,
- 'grant_type' => 'authorization_code'
- ];
- $url = $this->apiUrls['getUserInfo'];
- }
- $result = httpRequest($url, $data, 'get', '', 5);
- $this->saveLog($cacheKey . 'userInfo:request', ['code' => $code, 'url' => $url, 'query' => $data, 'result' => $result, 'date' => date('Y-m-d H:i:s')]);
- if (empty($result)) {
- $this->error = '获取用户信息失败';
- return false;
- }
- return $result;
- } catch (\Exception $e) {
- $this->error = $e->getMessage();
- $this->saveLog($cacheKey . 'userInfo:error', ['code' => $code, 'error' => $this->error, 'trace' => $e->getTrace(), 'date' => date('Y-m-d H:i:s')]);
- return false;
- }
- }
- /**
- * 公众号用户信息
- * @param $accessToken
- * @param $openid
- * @return array|false|mixed|string[]
- */
- public function getWechatUserInfo($accessToken, $openid)
- {
- try {
- $cacheKey = "caches:mpApp:wechat_{$openid}:";
- $url = sprintf($this->apiUrls['getWechatUserInfo'], $accessToken, $openid);
- $result = httpRequest($url, '', 'get', '', 5);
- $this->saveLog($cacheKey . 'wechatUserInfo:request', ['openid' => $openid, 'access_token' => $accessToken, 'url' => $url, 'result' => $result, 'date' => date('Y-m-d H:i:s')]);
- if (empty($result)) {
- $this->error = '获取用户信息失败';
- return false;
- }
- return $result;
- } catch (\Exception $e) {
- $this->error = $e->getMessage();
- $this->saveLog($cacheKey . 'userInfo:error', ['openid' => $openid, 'access_token' => $accessToken, 'error' => $this->error, 'trace' => $e->getTrace(), 'date' => date('Y-m-d H:i:s')]);
- return false;
- }
- }
- /**
- * 获取用户手机号码
- * @param $code
- * @return array|false|mixed|string[]
- */
- public function getPhoneNumber($code)
- {
- try {
- if (empty($code)) {
- $this->error = '缺少授权参数';
- return false;
- }
- if (empty($this->mpAppid) || empty($this->mpAppSecret)) {
- $this->error = '小程序参数未配置';
- return false;
- }
- if (!$token = $this->getAccessToken()) {
- $this->error = '获取token失败';
- return false;
- }
- $cacheKey = "caches:mpApp:mp_{$this->mpAppid}:";
- $url = sprintf($this->apiUrls['getPhoneNumber'], $token);
- $result = httpRequest($url, json_encode(['code' => $code], 256), 'post', '', 5);
- $this->saveLog($cacheKey . 'phone:request', ['code' => $code, 'url' => $url, 'result' => $result, 'date' => date('Y-m-d H:i:s')]);
- if (empty($result)) {
- $this->error = '获取用户手机号失败';
- return false;
- }
- return $result;
- } catch (\Exception $e) {
- $this->error = $e->getMessage();
- $this->saveLog($cacheKey . 'phone:error', ['code' => $code, 'error' => $this->error, 'trace' => $e->getTrace(), 'date' => date('Y-m-d H:i:s')]);
- return false;
- }
- }
- /**
- * 检验数据的真实性,并且获取解密后的明文.
- * @param $encryptedData string 加密的用户数据
- * @param $iv string 与用户数据一同返回的初始向量
- * @param $sessionKey string 解密会话KEY
- *
- * @return int 成功0,失败返回对应的错误码
- */
- public function decryptData($encryptedData, $iv, $sessionKey)
- {
- if (strlen($sessionKey) != 24) {
- $this->error = -41001;
- return false;
- }
- $aesKey = base64_decode($sessionKey);
- if (strlen($iv) != 24) {
- $this->error = -41002;
- return false;
- }
- $aesIV = base64_decode($iv);
- $aesCipher = base64_decode($encryptedData);
- $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
- $dataObj = json_decode($result);
- if ($dataObj == NULL) {
- $this->error = -41003;
- return false;
- }
- if ($dataObj->watermark->appid != $this->mpAppid) {
- $this->error = -41003;
- return false;
- }
- return $dataObj;
- }
- /**
- * 保存日志
- * @param $cackekey
- * @param $data
- * @param $time
- */
- public function saveLog($cackekey, $data, $time = 0)
- {
- if ($this->debug) {
- RedisService::set($cackekey, $data, $time ? $time : $this->expireTime);
- }
- }
- }
|