WechatServices.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 app\services\user\UserWechatuserServices;
  18. use crmeb\exceptions\ApiException;
  19. use crmeb\services\app\MiniProgramService;
  20. use crmeb\services\CacheService;
  21. use crmeb\services\app\WechatService as WechatAuthService;
  22. use crmeb\services\oauth\OAuth;
  23. use crmeb\services\pay\Pay;
  24. use crmeb\utils\Canvas;
  25. use think\facade\Db;
  26. use think\facade\Log;
  27. /**
  28. *
  29. * Class WechatServices
  30. * @package app\services\wechat
  31. * @method value(array $where, ?string $field)
  32. */
  33. class WechatServices extends BaseServices
  34. {
  35. /**
  36. * WechatServices constructor.
  37. * @param WechatUserDao $dao
  38. */
  39. public function __construct(WechatUserDao $dao)
  40. {
  41. $this->dao = $dao;
  42. }
  43. /**
  44. * 微信公众号服务
  45. * @return \think\Response
  46. * @throws \EasyWeChat\Server\BadRequestException
  47. */
  48. public function serve()
  49. {
  50. ob_clean();
  51. return WechatAuthService::serve();
  52. }
  53. /**
  54. * 微信公众号服务
  55. * @return \think\Response
  56. * @throws \EasyWeChat\Server\BadRequestException
  57. */
  58. public function miniServe()
  59. {
  60. ob_clean();
  61. return MiniProgramService::serve();
  62. }
  63. /**
  64. * 支付异步回调
  65. * @return string
  66. * @throws \EasyWeChat\Core\Exceptions\FaultException
  67. */
  68. public function notify()
  69. {
  70. ob_clean();
  71. return WechatAuthService::handleNotify()->getContent();
  72. }
  73. /**
  74. * v3支付回调
  75. * @return string
  76. * @throws \EasyWeChat\Core\Exceptions\FaultException
  77. * @author 等风来
  78. * @email 136327134@qq.com
  79. * @date 2022/9/22
  80. */
  81. public function v3notify()
  82. {
  83. /** @var Pay $pay */
  84. $pay = app()->make(Pay::class, ['v3_wechat_pay']);
  85. return $pay->handleNotify()->getContent();
  86. }
  87. /**
  88. * 公众号权限配置信息获取
  89. * @param $url
  90. * @return mixed
  91. */
  92. public function config($url)
  93. {
  94. return json_decode(WechatAuthService::jsSdk($url), true);
  95. }
  96. /**
  97. * 公众号授权登录,返回token
  98. * @param $spread
  99. * @return array
  100. * @throws \Psr\SimpleCache\InvalidArgumentException
  101. * @throws \think\db\exception\DataNotFoundException
  102. * @throws \think\db\exception\DbException
  103. * @throws \think\db\exception\ModelNotFoundException
  104. * @author: 吴汐
  105. * @email: 442384644@qq.com
  106. * @date: 2023/8/12
  107. */
  108. public function authLogin($spread = '', $agent_id = '',$goods_user_type = '')
  109. {
  110. /** @var OAuth $oauth */
  111. $oauth = app()->make(OAuth::class);
  112. $wechatInfo = $oauth->oauth();
  113. if (!isset($wechatInfo['nickname'])) {
  114. $wechatInfo = $oauth->getUserInfo($wechatInfo['openid']);
  115. if (!isset($wechatInfo['nickname']))
  116. throw new ApiException(410131);
  117. if (isset($wechatInfo['tagid_list']))
  118. $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
  119. } else {
  120. if (isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
  121. }
  122. $wechatInfo['user_type'] = 'wechat';
  123. $openid = $wechatInfo['openid'];
  124. /** @var WechatUserServices $wechatUserServices */
  125. $wechatUserServices = app()->make(WechatUserServices::class);
  126. $user = $wechatUserServices->getAuthUserInfo($openid, 'wechat');
  127. if(!empty($user['uid'])){
  128. /** @var UserWechatuserServices $userWechatUserServices */
  129. $userWechatUserServices = app()->make(UserWechatuserServices::class);
  130. $wechatUserInfo = $userWechatUserServices->getUserByUid($user['uid']);
  131. $real_goods_user_type = $wechatUserInfo['goods_user_type'];
  132. if(!is_null($goods_user_type)){
  133. $goods_user_type = (int)$goods_user_type;
  134. if($goods_user_type>0){
  135. $wechatInfo['goods_user_type'] = $goods_user_type;
  136. }else{
  137. if(empty($real_goods_user_type)){
  138. $wechatInfo['goods_user_type'] = $goods_user_type;
  139. }
  140. }
  141. }
  142. }
  143. $createData = [$openid, $wechatInfo, $spread, $agent_id, 'wechat', 'wechat'];
  144. $storeUserMobile = sys_config('store_user_mobile');
  145. if ($storeUserMobile && (($user && $user['phone'] == '') || !$user)) {
  146. $userInfoKey = md5($openid . '_' . time() . '_wechat');
  147. CacheService::set($userInfoKey, $createData, 7200);
  148. return ['bindPhone' => true, 'key' => $userInfoKey];
  149. }
  150. $user = $wechatUserServices->wechatOauthAfter($createData);
  151. $wechatUserServices->wechatUpdata([$user['uid'], $wechatInfo]);
  152. $unionid = $wechatInfo['unionid'];
  153. $this->readUserScore($user['uid'],$unionid);
  154. $token = $this->createToken((int)$user['uid'], 'api');
  155. if ($token) {
  156. app()->make(UserVisitServices::class)->loginSaveVisit($user);
  157. $token['bindPhone'] = false;
  158. return [
  159. 'token' => $token['token'],
  160. 'expires_time' => $token['params']['exp'],
  161. 'bindPhone' => false
  162. ];
  163. } else {
  164. throw new ApiException(410019);
  165. }
  166. }
  167. private function readUserScore($uid,$unionid){
  168. $params = [$unionid];
  169. $list = Db::query('select * from eb_score_record where uniond_id = ? and `status` = 0', $params);
  170. if(!empty($list)){
  171. foreach ($list as $record) {
  172. // Extract the parameters for the doAddScore function from the current record
  173. $score = $record['score'];
  174. $integration_status = $record['integration_status'];
  175. $title = $record['title'];
  176. $mark = $record['mark'];
  177. $order_id = $record['order_id'];
  178. $params = [$order_id];
  179. $affectedRows =Db::execute('update `eb_score_record` set `status` = 1,send_time = now() where `order_id` = ? and `status` = 0', $params);
  180. if($affectedRows>0){
  181. $result = $this->doAddScore($uid, $score, $integration_status, $title, $mark);
  182. }
  183. }
  184. }
  185. }
  186. private function doAddScore($uid,$score,$integration_status,$title,$mark){
  187. $userService = app()->make(UserServices::class);
  188. $data = array('integration' => $score,'integration_status'=>$integration_status);
  189. $data['title'] = $title;
  190. $data['mark'] = $mark;
  191. $data['is_other'] = true;
  192. $result = $userService->addScore($uid,$data);
  193. return $result;
  194. }
  195. /**
  196. * 公众号强制绑定手机号
  197. * @param $key
  198. * @param $phone
  199. * @return array
  200. * @throws \Psr\SimpleCache\InvalidArgumentException
  201. * @throws \think\db\exception\DataNotFoundException
  202. * @throws \think\db\exception\DbException
  203. * @throws \think\db\exception\ModelNotFoundException
  204. * @author: 吴汐
  205. * @email: 442384644@qq.com
  206. * @date: 2023/8/12
  207. */
  208. public function authBindingPhone($key, $phone)
  209. {
  210. [$openid, $wechatInfo, $spreadId, $agent_id, $login_type, $userType] = CacheService::get($key);
  211. $wechatInfo['phone'] = $phone;
  212. //写入用户信息
  213. $user = app()->make(WechatUserServices::class)->wechatOauthAfter([$openid, $wechatInfo, $spreadId, $agent_id, $login_type, $userType]);
  214. $token = $this->createToken((int)$user['uid'], 'api');
  215. if ($token) {
  216. app()->make(UserVisitServices::class)->loginSaveVisit($user);
  217. return [
  218. 'token' => $token['token'],
  219. 'expires_time' => $token['params']['exp'],
  220. 'bindName' => false
  221. ];
  222. } else {
  223. throw new ApiException(410019);
  224. }
  225. }
  226. /**
  227. * 获取关注二维码
  228. * @return string[]
  229. * @throws \Exception
  230. */
  231. public function follow()
  232. {
  233. $canvas = Canvas::instance();
  234. $path = 'uploads/follow/';
  235. $imageType = 'jpg';
  236. $name = 'follow';
  237. $siteUrl = sys_config('site_url');
  238. $imageUrl = $path . $name . '.' . $imageType;
  239. $canvas->setImageUrl('statics/qrcode/follow.png')->setImageHeight(720)->setImageWidth(500)->pushImageValue();
  240. $wechatQrcode = sys_config('wechat_qrcode');
  241. if (($strlen = stripos($wechatQrcode, 'uploads')) !== false) {
  242. $wechatQrcode = substr($wechatQrcode, $strlen);
  243. }
  244. if (!$wechatQrcode)
  245. throw new ApiException(410081);
  246. $canvas->setImageUrl($wechatQrcode)->setImageHeight(344)->setImageWidth(344)->setImageLeft(76)->setImageTop(76)->pushImageValue();
  247. $image = $canvas->setFileName($name)->setImageType($imageType)->setPath($path)->setBackgroundWidth(500)->setBackgroundHeight(720)->starDrawChart();
  248. return ['path' => $image ? $siteUrl . '/' . $image : ''];
  249. }
  250. /**
  251. * 是否关注
  252. * @param int $uid
  253. * @return bool
  254. */
  255. public function isSubscribe(int $uid)
  256. {
  257. if ($uid) {
  258. $subscribe = (bool)$this->dao->value(['uid' => $uid], 'subscribe');
  259. } else {
  260. $subscribe = true;
  261. }
  262. return $subscribe;
  263. }
  264. /**
  265. * app登录
  266. * @param array $userData
  267. * @param string $phone
  268. * @param string $userType
  269. * @return array|false
  270. * @throws \think\db\exception\DataNotFoundException
  271. * @throws \think\db\exception\ModelNotFoundException
  272. */
  273. public function appAuth(array $userData, string $phone, string $userType = 'app')
  274. {
  275. $openid = $userData['openId'] ?? "";
  276. $userInfo = [
  277. 'phone' => $phone,
  278. 'unionid' => $userData['unionId'] ?? '',
  279. 'headimgurl' => $userData['avatarUrl'] ?? '',
  280. 'nickname' => $userData['nickName'] ?? '',
  281. 'province' => $userData['province'] ?? '',
  282. 'country' => $userData['country'] ?? '',
  283. 'city' => $userData['city'] ?? '',
  284. 'openid' => $openid,
  285. ];
  286. $login_type = $userType;
  287. $spreadId = $userInfo['spreadId'] ?? "";
  288. if (!$phone) {
  289. //获取是否强制绑定手机号
  290. $storeUserMobile = sys_config('store_user_mobile');
  291. if ($userInfo['unionid'] && $storeUserMobile) {
  292. /** @var UserServices $userServices */
  293. $userServices = app()->make(UserServices::class);
  294. $uid = $this->dao->value(['unionid' => $userInfo['unionid'], 'is_del' => 0], 'uid');
  295. $res = $userServices->value(['uid' => $uid, 'is_del' => 0], 'phone');
  296. if (!$uid && !$res) {
  297. return false;
  298. }
  299. } elseif ($openid && $storeUserMobile) {
  300. /** @var UserServices $userServices */
  301. $userServices = app()->make(UserServices::class);
  302. $uid = $this->dao->value(['openid' => $openid], 'uid');
  303. $res = $userServices->value(['uid' => $uid], 'phone');
  304. if (!$uid && !$res) {
  305. return false;
  306. }
  307. }
  308. }
  309. /** @var WechatUserServices $wechatUser */
  310. $wechatUser = app()->make(WechatUserServices::class);
  311. //更新用户信息
  312. $user = $wechatUser->wechatOauthAfter([$openid, $userInfo, $spreadId, 0, $login_type, $userType]);
  313. $token = $this->createToken((int)$user['uid'], 'api');
  314. if ($token) {
  315. /** @var UserVisitServices $visitServices */
  316. $visitServices = app()->make(UserVisitServices::class);
  317. $visitServices->loginSaveVisit($user);
  318. return [
  319. 'token' => $token['token'],
  320. 'userInfo' => $user,
  321. 'expires_time' => $token['params']['exp'],
  322. 'isbind' => false
  323. ];
  324. } else
  325. throw new ApiException(410019);
  326. }
  327. }