WechatController.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. <?php
  2. namespace app\api\controller\wechat;
  3. use app\models\user\User;
  4. use app\models\user\UserToken;
  5. use app\models\user\WechatUser;
  6. use app\models\user\BindUser;
  7. use app\models\store\StoreOrder;
  8. use app\models\system\MerchantDailyReport;
  9. use app\Request;
  10. use crmeb\services\WechatService;
  11. use crmeb\services\UtilService;
  12. use crmeb\utils\Canvas;
  13. use think\facade\Cookie;
  14. /**
  15. * 微信公众号
  16. * Class WechatController
  17. * @package app\api\controller\wechat
  18. */
  19. class WechatController
  20. {
  21. //公众号appid
  22. const APPID = 'wx850b73fe48f1e931';
  23. //公众号appsecret
  24. const APP_SECRET = 'e1a17191ca4e91657932df9a13a09886';
  25. /**
  26. * 微信公众号服务
  27. * @return \think\Response
  28. */
  29. public function serve()
  30. {
  31. ob_clean();
  32. return WechatService::serve();
  33. }
  34. /**
  35. * 支付异步回调
  36. */
  37. public function notify()
  38. {
  39. ob_clean();
  40. WechatService::handleNotify();
  41. }
  42. /**
  43. * 公众号权限配置信息获取
  44. * @param Request $request
  45. * @return mixed
  46. */
  47. public function config(Request $request)
  48. {
  49. return app('json')->success(json_decode(WechatService::jsSdk($request->get('url')), true));
  50. }
  51. /**
  52. * 公众号授权登陆
  53. * @param Request $request
  54. * @return mixed
  55. * @throws \think\db\exception\DataNotFoundException
  56. * @throws \think\db\exception\ModelNotFoundException
  57. * @throws \think\exception\DbException
  58. */
  59. public function auth(Request $request)
  60. {
  61. $spreadId = intval($request->param('spread'));
  62. $login_type = $request->param('login_type', '');
  63. try {
  64. $wechatInfo = WechatService::oauthService()->user()->getOriginal();
  65. } catch (\Exception $e) {
  66. return app('json')->fail('授权失败', ['message' => $e->getMessage(), 'line' => $e->getLine()]);
  67. }
  68. if (!isset($wechatInfo['nickname'])) {
  69. $wechatInfo = WechatService::getUserInfo($wechatInfo['openid']);
  70. if (!$wechatInfo['subscribe'] && !isset($wechatInfo['nickname']))
  71. exit(WechatService::oauthService()->scopes(['snsapi_userinfo'])
  72. ->redirect($this->request->url(true))->send());
  73. if (isset($wechatInfo['tagid_list']))
  74. $wechatInfo['tagid_list'] = implode(',', $wechatInfo['tagid_list']);
  75. } else {
  76. if (isset($wechatInfo['privilege'])) unset($wechatInfo['privilege']);
  77. if (!WechatUser::be(['openid' => $wechatInfo['openid']]))
  78. $wechatInfo['subscribe'] = 0;
  79. }
  80. $openid = $wechatInfo['openid'];
  81. event('WechatOauthAfter', [$openid, $wechatInfo, $spreadId, $login_type]);
  82. $user = User::where('uid', WechatUser::openidToUid($openid, 'openid'))->find();
  83. if (!$user)
  84. return app('json')->fail('获取用户信息失败');
  85. if ($user->login_type == 'h5' && ($h5UserInfo = User::where(['account' => $user->phone, 'phone' => $user->phone, 'user_type' => 'h5'])->find()))
  86. $token = UserToken::createToken($h5UserInfo, 'wechat');
  87. else
  88. $token = UserToken::createToken($user, 'wechat');
  89. // 设置推广关系
  90. User::setSpread(intval($spreadId), $user->uid);
  91. if ($token) {
  92. event('UserLogin', [$user, $token]);
  93. return app('json')->success('登录成功', ['token' => $token['token'], 'expires_time' => date('Y-m-d H:i:s', $token['params']['exp'])]);
  94. } else
  95. return app('json')->fail('登录失败');
  96. }
  97. /**
  98. * 公众号网页授权登陆
  99. */
  100. public function wxAuth(Request $request)
  101. {
  102. $mer_id = $request->param('mer_id', '');
  103. $redirect_uri=urlencode("https://auti.boofly.cn/api/wechat/bindPush");
  104. header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.self::APPID.'&redirect_uri='.$redirect_uri.'&response_type=code&scope=snsapi_userinfo&state='.$mer_id.'#wechat_redirect');
  105. }
  106. /**
  107. * 公众号绑定推送
  108. */
  109. public function bindPush(Request $request)
  110. {
  111. try {
  112. $data = UtilService::getMore([
  113. ['code', ''],
  114. ['state', ''],
  115. ]);
  116. $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.self::APPID.'&secret='.self::APP_SECRET.'&code='.$data['code'].'&grant_type=authorization_code';
  117. $res = json_decode(doRequest($url, [], null, false), true);
  118. if (isset($res['errcode']) && $res['errcode'] != 0) {
  119. return app('json')->fail($res['errmsg'] ?? $res['msg'] ?? '请求错误');
  120. }
  121. $result = $this->getUserInfo($res['access_token'], $res['openid']);
  122. return app('json')->success('ok', $result);
  123. } catch (Exception $e) {
  124. return app('json')->fail($e->getMessage(), ['file' => $e->getFile(), 'line' => $e->getLine()]);
  125. }
  126. }
  127. /**
  128. * 拉取用户信息
  129. */
  130. public function getUserInfo($access_token, $openid)
  131. {
  132. try {
  133. $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='. $access_token. '&openid='. $openid. '&lang=zh_CN';
  134. $res = json_decode(doRequest($url, [], null, false), true);
  135. if (isset($res['errcode']) && $res['errcode'] != 0) {
  136. return app('json')->fail($res['errmsg'] ?? $res['msg'] ?? '请求错误');
  137. }
  138. return $res;
  139. } catch (Exception $e) {
  140. return app('json')->fail($e->getMessage(), ['file' => $e->getFile(), 'line' => $e->getLine()]);
  141. }
  142. }
  143. /**
  144. * 用户信息入库
  145. */
  146. public function addUserInfo(Request $request)
  147. {
  148. try {
  149. $data = UtilService::postMore([
  150. ['openid', ''],
  151. ['nickname', ''],
  152. ['sex', ''],
  153. ['language', ''],
  154. ['city', ''],
  155. ['province', ''],
  156. ['country', ''],
  157. ['headimgurl', ''],
  158. ['state', '']
  159. ]);
  160. $type = 1;
  161. $status = 1;
  162. $info = BindUser::where('openid', $data['openid'])->where('is_del', 0)->find();
  163. if($info){
  164. BindUser::where('id', $info['id'])->update(['openid' => $data['openid'], 'nickname' => $data['nickname'], 'sex' => $data['sex'], 'language' => $data['language'], 'city' => $data['city'], 'province' => $data['province'], 'country' => $data['country'], 'headimgurl' => $data['headimgurl']]);
  165. }else{
  166. $res = BindUser::addBindUser($data['openid'], $data['nickname'], $data['sex'], $data['language'], $data['city'], $data['province'], $data['country'], $data['headimgurl'], $type, $status, $data['state']);
  167. if(!$res){
  168. return app('json')->fail('入库失败');
  169. }
  170. }
  171. return app('json')->success('入库成功');
  172. } catch (Exception $e) {
  173. return app('json')->fail($e->getMessage(), ['file' => $e->getFile(), 'line' => $e->getLine()]);
  174. }
  175. }
  176. /**
  177. * 统计报表列表
  178. */
  179. public function getReportList(Request $request)
  180. {
  181. $data = UtilService::getMore([
  182. ['mer_id', ''],
  183. ['date', '']
  184. ]);
  185. $model = new MerchantDailyReport;
  186. if($data['mer_id']) $model = $model->where('mer_id', $data['mer_id']);
  187. if($data['date']) $model = $model->where('report_date', $data['date']);
  188. $yesterday = $model->find();
  189. //总销售额
  190. $total_sales = StoreOrder::merSet($data['mer_id'])
  191. ->where('paid', 1)
  192. ->where('is_del', 0)
  193. ->where('refund_status', 0)
  194. ->sum('pay_price');
  195. //总访问量
  196. $total_visits = User::merSet($data['mer_id'])->count();
  197. //总订单量
  198. $total_order = StoreOrder::merSet($data['mer_id'])->where('is_system_del', 0)->count();
  199. //所有用户
  200. $total_user = User::merSet($data['mer_id'])->count();
  201. $total = [
  202. 'total_sales' => $total_sales . '元',
  203. 'total_visits' => $total_visits . 'Pv',
  204. 'total_order' => $total_order . '单',
  205. 'total_user' => $total_user . '人',
  206. ];
  207. $info = compact('yesterday', 'total');
  208. return app('json')->success($info);
  209. }
  210. public function follow(Request $request)
  211. {
  212. $canvas = Canvas::instance();
  213. $path = 'uploads/follow/';
  214. $imageType = 'jpg';
  215. $name = 'follow';
  216. $siteUrl = sys_config('site_url', '', $request->mer_id());
  217. $imageUrl = $path . $name . '.' . $imageType;
  218. // if (file_exists($imageUrl)) {
  219. // return app('json')->success('ok', ['path' => $siteUrl . '/' . $imageUrl]);
  220. // }
  221. $canvas->setImageUrl('statics/qrcode/follow.png')->setImageHeight(720)->setImageWidth(500)->pushImageValue();
  222. $wechatQrcode = sys_config('wechat_qrcode', '', $request->mer_id());
  223. if (($strlen = stripos($wechatQrcode, 'uploads')) !== false) {
  224. $wechatQrcode = substr($wechatQrcode, $strlen);
  225. }
  226. if (!$wechatQrcode)
  227. return app('json')->fail('请上传二维码');
  228. $canvas->setImageUrl($wechatQrcode)->setImageHeight(344)->setImageWidth(344)->setImageLeft(76)->setImageTop(76)->pushImageValue();
  229. $image = $canvas->setFileName($name)->setImageType($imageType)->setPath($path)->setBackgroundWidth(500)->setBackgroundHeight(720)->starDrawChart();
  230. return app('json')->success('ok', ['path' => $image ? $siteUrl . '/' . $image : '']);
  231. }
  232. }