WechatServices.php 12 KB

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