WechatServices.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. declare (strict_types=1);
  12. namespace app\services\wechat;
  13. use app\services\BaseServices;
  14. use app\dao\wechat\WechatUserDao;
  15. use app\services\user\UserServices;
  16. use app\services\user\UserVisitServices;
  17. use crmeb\exceptions\ApiException;
  18. use crmeb\services\CacheService;
  19. use crmeb\services\CacheService as Cache;
  20. use crmeb\services\app\WechatService as WechatAuthService;
  21. use crmeb\services\oauth\OAuth;
  22. use crmeb\services\pay\Pay;
  23. use crmeb\utils\Canvas;
  24. /**
  25. *
  26. * Class WechatServices
  27. * @package app\services\wechat
  28. * @method value(array $where, ?string $field)
  29. */
  30. class WechatServices extends BaseServices
  31. {
  32. /**
  33. * WechatServices constructor.
  34. * @param WechatUserDao $dao
  35. */
  36. public function __construct(WechatUserDao $dao)
  37. {
  38. $this->dao = $dao;
  39. }
  40. /**
  41. * 微信公众号服务
  42. * @return \think\Response
  43. * @throws \EasyWeChat\Server\BadRequestException
  44. */
  45. public function serve()
  46. {
  47. ob_clean();
  48. return WechatAuthService::serve();
  49. }
  50. /**
  51. * 支付异步回调
  52. * @return string
  53. * @throws \EasyWeChat\Core\Exceptions\FaultException
  54. */
  55. public function notify()
  56. {
  57. ob_clean();
  58. return WechatAuthService::handleNotify()->getContent();
  59. }
  60. /**
  61. * v3支付回调
  62. * @return string
  63. * @throws \EasyWeChat\Core\Exceptions\FaultException
  64. * @author 等风来
  65. * @email 136327134@qq.com
  66. * @date 2022/9/22
  67. */
  68. public function v3notify()
  69. {
  70. /** @var Pay $pay */
  71. $pay = app()->make(Pay::class, ['v3_wechat_pay']);
  72. return $pay->handleNotify()->getContent();
  73. }
  74. /**
  75. * 公众号权限配置信息获取
  76. * @param $url
  77. * @return mixed
  78. */
  79. public function config($url)
  80. {
  81. return json_decode(WechatAuthService::jsSdk($url), true);
  82. }
  83. /**
  84. * 公众号授权登陆
  85. * @return mixed
  86. * @throws \think\db\exception\DataNotFoundException
  87. * @throws \think\db\exception\ModelNotFoundException
  88. * @throws \think\exception\DbException
  89. */
  90. public function auth($spreadId, $login_type)
  91. {
  92. /** @var OAuth $oauth */
  93. $oauth = app()->make(OAuth::class);
  94. $wechatInfo = $oauth->oauth();
  95. if (!isset($wechatInfo['nickname'])) {
  96. $wechatInfo = $oauth->getUserInfo($wechatInfo['openid']);
  97. if (!isset($wechatInfo['nickname']))
  98. throw new ApiException(410131);
  99. if (isset($wechatInfo['tagid_list']))
  100. $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
  101. } else {
  102. if (isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
  103. /** @var WechatUserServices $wechatUser */
  104. $wechatUser = app()->make(WechatUserServices::class);
  105. if (!$wechatUser->getOne(['openid' => $wechatInfo['openid']])) {
  106. $wechatInfo['subscribe'] = 0;
  107. }
  108. }
  109. $wechatInfo['user_type'] = 'wechat';
  110. $openid = $wechatInfo['openid'];
  111. /** @var WechatUserServices $wechatUserServices */
  112. $wechatUserServices = app()->make(WechatUserServices::class);
  113. $user = $wechatUserServices->getAuthUserInfo($openid, 'wechat');
  114. $createData = [$openid, $wechatInfo, $spreadId, $login_type, 'wechat'];
  115. if (!$user) {
  116. $user = $wechatUserServices->wechatOauthAfter($createData);
  117. } else {
  118. if (!$user['status']) throw new ApiException(410027);
  119. //更新用户信息
  120. $wechatUserServices->wechatUpdata([$user['uid'], $wechatInfo]);
  121. }
  122. $token = $this->createToken((int)$user['uid'], 'api');
  123. if ($token) {
  124. /** @var UserVisitServices $visitServices */
  125. $visitServices = app()->make(UserVisitServices::class);
  126. $visitServices->loginSaveVisit($user);
  127. return ['userInfo' => $user];
  128. } else
  129. throw new ApiException(410019);
  130. }
  131. /**
  132. * 新公众号授权登录
  133. * @return mixed
  134. * @throws \think\db\exception\DataNotFoundException
  135. * @throws \think\db\exception\ModelNotFoundException
  136. * @throws \think\exception\DbException
  137. */
  138. public function newAuth($spreadId, $login_type)
  139. {
  140. /** @var OAuth $oauth */
  141. $oauth = app()->make(OAuth::class);
  142. $wechatInfo = $oauth->oauth();
  143. if (!isset($wechatInfo['nickname'])) {
  144. $wechatInfo = $oauth->getUserInfo($wechatInfo['openid']);
  145. if (!isset($wechatInfo['nickname']))
  146. throw new ApiException(410131);
  147. if (isset($wechatInfo['tagid_list']))
  148. $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
  149. } else {
  150. if (isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
  151. }
  152. $wechatInfo['user_type'] = 'wechat';
  153. $openid = $wechatInfo['openid'];
  154. /** @var WechatUserServices $wechatUserServices */
  155. $wechatUserServices = app()->make(WechatUserServices::class);
  156. $user = $wechatUserServices->getAuthUserInfo($openid, 'wechat');
  157. $createData = [$openid, $wechatInfo, $spreadId, $login_type, 'wechat'];
  158. //获取是否强制绑定手机号
  159. $storeUserMobile = sys_config('store_user_mobile');
  160. if ($storeUserMobile && !$user) {
  161. $userInfoKey = md5($openid . '_' . time() . '_wechat');
  162. Cache::set($userInfoKey, $createData, 7200);
  163. return ['key' => $userInfoKey];
  164. } else if (!$user) {
  165. $user = $wechatUserServices->wechatOauthAfter($createData);
  166. } else {
  167. if (!$user['status']) throw new ApiException(410027);
  168. //更新用户信息
  169. $wechatUserServices->wechatUpdata([$user['uid'], $wechatInfo]);
  170. }
  171. $token = $this->createToken((int)$user['uid'], 'api');
  172. if ($token) {
  173. /** @var UserVisitServices $visitServices */
  174. $visitServices = app()->make(UserVisitServices::class);
  175. $visitServices->loginSaveVisit($user);
  176. $token['userInfo'] = $user;
  177. return $token;
  178. } else
  179. throw new ApiException(410019);
  180. }
  181. /**
  182. * 获取关注二维码
  183. * @return string[]
  184. * @throws \Exception
  185. */
  186. public function follow()
  187. {
  188. $canvas = Canvas::instance();
  189. $path = 'uploads/follow/';
  190. $imageType = 'jpg';
  191. $name = 'follow';
  192. $siteUrl = sys_config('site_url');
  193. $imageUrl = $path . $name . '.' . $imageType;
  194. $canvas->setImageUrl('statics/qrcode/follow.png')->setImageHeight(720)->setImageWidth(500)->pushImageValue();
  195. $wechatQrcode = sys_config('wechat_qrcode');
  196. if (($strlen = stripos($wechatQrcode, 'uploads')) !== false) {
  197. $wechatQrcode = substr($wechatQrcode, $strlen);
  198. }
  199. if (!$wechatQrcode)
  200. throw new ApiException(410081);
  201. $canvas->setImageUrl($wechatQrcode)->setImageHeight(344)->setImageWidth(344)->setImageLeft(76)->setImageTop(76)->pushImageValue();
  202. $image = $canvas->setFileName($name)->setImageType($imageType)->setPath($path)->setBackgroundWidth(500)->setBackgroundHeight(720)->starDrawChart();
  203. return ['path' => $image ? $siteUrl . '/' . $image : ''];
  204. }
  205. /**
  206. * 微信公众号静默授权
  207. * @param $spread
  208. * @return array
  209. * @throws \think\db\exception\DataNotFoundException
  210. * @throws \think\db\exception\ModelNotFoundException
  211. */
  212. public function silenceAuth($spread)
  213. {
  214. /** @var OAuth $oauth */
  215. $oauth = app()->make(OAuth::class);
  216. $wechatInfoConfig = $oauth->oauth();
  217. $wechatInfo = $oauth->getUserInfo($wechatInfoConfig['openid']);
  218. $openid = $wechatInfoConfig['openid'];
  219. /** @var WechatUserServices $wechatUserServices */
  220. $wechatUserServices = app()->make(WechatUserServices::class);
  221. $user = $wechatUserServices->getAuthUserInfo($openid, 'wechat');
  222. $wechatInfo['headimgurl'] = isset($wechatInfo['headimgurl']) && $wechatInfo['headimgurl'] != '' ? $wechatInfo['headimgurl'] : sys_config('h5_avatar');
  223. $createData = [$openid, $wechatInfo, $spread, '', 'wechat'];
  224. //获取是否强制绑定手机号
  225. $storeUserMobile = sys_config('store_user_mobile');
  226. if ($storeUserMobile && !$user) {
  227. $userInfoKey = md5($openid . '_' . time() . '_wechat');
  228. Cache::set($userInfoKey, $createData, 7200);
  229. return ['key' => $userInfoKey];
  230. } else if (!$user) {
  231. //写入用户信息
  232. $user = $wechatUserServices->wechatOauthAfter($createData);
  233. $token = $this->createToken((int)$user['uid'], 'api');
  234. if ($token) {
  235. /** @var UserVisitServices $visitServices */
  236. $visitServices = app()->make(UserVisitServices::class);
  237. $visitServices->loginSaveVisit($user);
  238. return $token;
  239. } else
  240. throw new ApiException(410019);
  241. } else {
  242. //更新用户信息
  243. $wechatUserServices->wechatUpdata([$user['uid'], ['code' => $spread]]);
  244. $token = $this->createToken((int)$user['uid'], 'api');
  245. if ($token) {
  246. /** @var UserVisitServices $visitServices */
  247. $visitServices = app()->make(UserVisitServices::class);
  248. $visitServices->loginSaveVisit($user);
  249. return $token;
  250. } else
  251. throw new ApiException(410019);
  252. }
  253. }
  254. /**
  255. * 微信公众号静默授权(不登录注册用户)
  256. * @param $spread
  257. * @return array
  258. * @throws \think\db\exception\DataNotFoundException
  259. * @throws \think\db\exception\ModelNotFoundException
  260. */
  261. public function silenceAuthNoLogin($spread)
  262. {
  263. /** @var OAuth $oauth */
  264. $oauth = app()->make(OAuth::class);
  265. $wechatInfoConfig = $oauth->oauth();
  266. $openid = $wechatInfoConfig['openid'];
  267. try {
  268. $wechatInfo = $oauth->getUserInfo($wechatInfoConfig['openid']);
  269. } catch (\Throwable $e) {
  270. $createData = [$openid, [], $spread, '', 'wechat'];
  271. $userInfoKey = md5($openid . '_' . time() . '_wechat');
  272. Cache::set($userInfoKey, $createData, 7200);
  273. return ['auth_login' => 1, 'key' => $userInfoKey];
  274. }
  275. /** @var WechatUserServices $wechatUserServices */
  276. $wechatUserServices = app()->make(WechatUserServices::class);
  277. $user = $wechatUserServices->getAuthUserInfo($openid, 'wechat');
  278. $createData = [$openid, $wechatInfo, $spread, '', 'wechat'];
  279. $userInfoKey = md5($openid . '_' . time() . '_wechat');
  280. Cache::set($userInfoKey, $createData, 7200);
  281. return ['auth_login' => 1, 'key' => $userInfoKey];
  282. }
  283. /**
  284. * 微信公众号静默授权
  285. * @param $key
  286. * @param $phone
  287. * @return array
  288. * @throws \Psr\SimpleCache\InvalidArgumentException
  289. * @throws \think\db\exception\DataNotFoundException
  290. * @throws \think\db\exception\ModelNotFoundException
  291. */
  292. public function silenceAuthBindingPhone($key, $phone)
  293. {
  294. if (!$key) {
  295. throw new ApiException(410037);
  296. }
  297. [$openid, $wechatInfo, $spreadId, $login_type, $userType] = $createData = CacheService::get($key);
  298. if (!$createData) {
  299. throw new ApiException(410037);
  300. }
  301. $wechatInfo['phone'] = $phone;
  302. /** @var WechatUserServices $wechatUser */
  303. $wechatUser = app()->make(WechatUserServices::class);
  304. //更新用户信息
  305. $user = $wechatUser->wechatOauthAfter([$openid, $wechatInfo, $spreadId, $login_type, $userType]);
  306. $token = $this->createToken((int)$user['uid'], 'api');
  307. if ($token) {
  308. /** @var UserVisitServices $visitServices */
  309. $visitServices = app()->make(UserVisitServices::class);
  310. $visitServices->loginSaveVisit($user);
  311. return [
  312. 'token' => $token['token'],
  313. 'userInfo' => $user,
  314. 'expires_time' => $token['params']['exp'],
  315. ];
  316. } else
  317. throw new ApiException(410019);
  318. }
  319. /**
  320. * 是否关注
  321. * @param int $uid
  322. * @return bool
  323. */
  324. public function isSubscribe(int $uid)
  325. {
  326. if ($uid) {
  327. $subscribe = (bool)$this->dao->value(['uid' => $uid], 'subscribe');
  328. } else {
  329. $subscribe = true;
  330. }
  331. return $subscribe;
  332. }
  333. /**
  334. * app登录
  335. * @param array $userData
  336. * @param string $phone
  337. * @param string $userType
  338. * @return array|false
  339. * @throws \think\db\exception\DataNotFoundException
  340. * @throws \think\db\exception\ModelNotFoundException
  341. */
  342. public function appAuth(array $userData, string $phone, string $userType = 'app')
  343. {
  344. $openid = $userData['openId'] ?? "";
  345. $userInfo = [
  346. 'phone' => $phone,
  347. 'unionid' => $userData['unionId'] ?? '',
  348. 'headimgurl' => $userData['avatarUrl'] ?? '',
  349. 'nickname' => $userData['nickName'] ?? '',
  350. 'province' => $userData['province'] ?? '',
  351. 'country' => $userData['country'] ?? '',
  352. 'city' => $userData['city'] ?? '',
  353. 'openid' => $openid,
  354. ];
  355. $login_type = $userType;
  356. $spreadId = $userInfo['spreadId'] ?? "";
  357. if (!$phone) {
  358. //获取是否强制绑定手机号
  359. $storeUserMobile = sys_config('store_user_mobile');
  360. if ($userInfo['unionid'] && $storeUserMobile) {
  361. /** @var UserServices $userServices */
  362. $userServices = app()->make(UserServices::class);
  363. $uid = $this->dao->value(['unionid' => $userInfo['unionid'], 'is_del' => 0], 'uid');
  364. $res = $userServices->value(['uid' => $uid, 'is_del' => 0], 'phone');
  365. if (!$uid && !$res) {
  366. return false;
  367. }
  368. }
  369. if ($openid && $storeUserMobile) {
  370. /** @var UserServices $userServices */
  371. $userServices = app()->make(UserServices::class);
  372. $uid = $this->dao->value(['openid' => $openid], 'uid');
  373. $res = $userServices->value(['uid' => $uid], 'phone');
  374. if (!$uid && !$res) {
  375. return false;
  376. }
  377. }
  378. }
  379. /** @var WechatUserServices $wechatUser */
  380. $wechatUser = app()->make(WechatUserServices::class);
  381. //更新用户信息
  382. $user = $wechatUser->wechatOauthAfter([$openid, $userInfo, $spreadId, $login_type, $userType]);
  383. $token = $this->createToken((int)$user['uid'], 'api');
  384. if ($token) {
  385. /** @var UserVisitServices $visitServices */
  386. $visitServices = app()->make(UserVisitServices::class);
  387. $visitServices->loginSaveVisit($user);
  388. return [
  389. 'token' => $token['token'],
  390. 'userInfo' => $user,
  391. 'expires_time' => $token['params']['exp'],
  392. 'isbind' => false
  393. ];
  394. } else
  395. throw new ApiException(410019);
  396. }
  397. }