UsersController.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. <?php
  2. namespace App\Http\Controllers\KuaiYingYong\Oauth;
  3. use App\Modules\User\Services\UserService;
  4. use App\Modules\Xcx\Services\XcxSendOrderService;
  5. use Illuminate\Http\Request;
  6. use App\Http\Controllers\Controller;
  7. use App\Modules\User\Models\User;
  8. use App\Modules\User\Models\Xcxuser;
  9. use Log;
  10. use JWTAuth;
  11. use GuzzleHttp\Client;
  12. class UsersController extends Controller
  13. {
  14. /**
  15. * @apiDefine Login 登录
  16. */
  17. /**
  18. * @apiVersion 1.0.0
  19. * @apiDescription 登录
  20. * @api {post} login 登录
  21. * @apiParam {String} js_code js_code
  22. * @apiParam {Int} distribution_channel_id distribution_channel_id
  23. * @apiParam {String} sign 签名
  24. * @apiGroup Login
  25. * @apiName index
  26. * @apiSuccess {int} code 状态码
  27. * @apiSuccess {String} msg 信息
  28. * @apiSuccess {object} data 结果集
  29. * @apiSuccess {String} data.token token
  30. * @apiSuccess {Int} data.time 过期时间
  31. * @apiSuccessExample {json} Success-Response:
  32. * HTTP/1.1 200 OK
  33. * {
  34. * code: 0,
  35. * msg: "",
  36. * data: {
  37. * token:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
  38. * time:123455
  39. * }
  40. * }
  41. */
  42. public function index(Request $request)
  43. {
  44. Log::info($request->all());
  45. //$distribution_channel_id = $request->input('distribution_channel_id', '');
  46. //海报推广的参数
  47. $scene = $request->input('scene', '');
  48. $js_code = $request->input('js_code');
  49. $sign = $request->input('sign');
  50. $encryptedData = $request->input('encryptedData');
  51. $iv = $request->input('iv');
  52. //参数推广的参数
  53. $channel_key = $request->input('channel_key',0);
  54. $sign = 1;
  55. if (empty($js_code) || empty($sign)) {
  56. return response()->error('PARAM_ERROR');
  57. }
  58. $distribution_channel_id = 14;
  59. $uid = 0;
  60. $u = 0;
  61. //解析海报推广的参数
  62. if($scene){
  63. $scene_arr = explode('_',$scene);
  64. $distribution_channel_id = (int)$scene_arr[0];
  65. $uid = $scene_arr[1];
  66. $u = $scene_arr[2];
  67. }
  68. //解析参数推广的参数
  69. if($channel_key){
  70. $channel_key =(int)$channel_key;
  71. $channel_info = XcxSendOrderService::getChannelIdBySendOrderId($channel_key);
  72. if($channel_info){
  73. $distribution_channel_id = $channel_info->distribution_channel_id;
  74. $u = $channel_key;
  75. }
  76. }
  77. if ($sign !== _sign(compact('openid', 'distribution_channel_id', 'unionid'), 'Uv%vkPI5K8Opqoww')) {
  78. //return response()->error('PARAM_ERROR');
  79. }
  80. $login_info = $this->getUserWeixinInfo($js_code);
  81. $appid = 'wxa0c8331eba3b34d5';
  82. $status = $this->decryptData($appid,$login_info['session_key'],$encryptedData,$iv,$user_info);
  83. if($status != ErrorCode::$OK){
  84. return response()->error('PARAM_ERROR');
  85. }
  86. if (!$user_info) response()->error('PARAM_ERROR');
  87. $user_info = json_decode($user_info,1);
  88. if (!isset($user_info['openId']) || !isset($user_info['unionId'])) {
  89. return response()->error('PARAM_ERROR');
  90. }
  91. $openid = $user_info['openId'];
  92. $unionid = $user_info['unionId'];
  93. $user = $this->createUser(compact('openid', 'distribution_channel_id', 'unionid','uid','u'),$user_info);
  94. if ($user) {
  95. $uid = $user->id;
  96. $time = time() + 7200;
  97. $token = JWTAuth::fromUser($user);
  98. return response()->success(compact('token', 'time','uid'));
  99. } else {
  100. return response()->error('PARAM_ERROR');
  101. }
  102. }
  103. /**
  104. * 授权用户信息
  105. * @param $data
  106. * @return bool
  107. */
  108. protected function createUser($data,$user_info)
  109. {
  110. //compact('openid', 'distribution_channel_id', 'unionid','uid','u')
  111. //用户已经是小程序用户了
  112. $xcx_user = Xcxuser::where('unionid',$data['unionid'])
  113. ->where('distribution_channel_id',$data['distribution_channel_id'])
  114. ->select('uid')
  115. ->first();
  116. if($xcx_user){
  117. return User::find($xcx_user->uid);
  118. }
  119. $info = [];
  120. if(isset($user_info['city']) && !empty($user_info['city'])) {$info['city'] = $user_info['city'];}
  121. if(isset($user_info['province']) && !empty($user_info['province'])){ $info['province'] = $user_info['province'];}
  122. if(isset($user_info['country']) && !empty($user_info['country'])){ $info['country'] = $user_info['country'];}
  123. if(isset($user_info['gender']) && !empty($user_info['gender'])) {$info['sex'] = $user_info['gender'];}
  124. if(isset($user_info['nickName']) && !empty($user_info['nickName'])) {$info['nickname'] = $user_info['nickName'];}
  125. if(isset($user_info['avatarUrl']) && !empty($user_info['avatarUrl'])) {$info['head_img'] = $user_info['avatarUrl'];}
  126. //从推广进来的一般会有uid
  127. if($data['uid']){
  128. Xcxuser::create([
  129. 'uid'=>$data['uid'],
  130. 'openid'=>$data['openid'],
  131. 'unionid'=>$data['unionid'],
  132. 'distribution_channel_id'=>$data['distribution_channel_id'],
  133. 'u'=>$data['u']
  134. ]);
  135. if($info){
  136. UserService::updateInfo($data['uid'],$info);
  137. }
  138. return User::find($data['uid']);
  139. }else{
  140. //直接进入的
  141. $info['openid'] =$data['openid'];
  142. $info['unionid'] =$data['openid'];
  143. $info['distribution_channel_id'] =$data['distribution_channel_id'];
  144. $info['send_order_id'] =$data['u'];
  145. $user = User::addUser($info);
  146. Xcxuser::create([
  147. 'uid'=>$user->id,
  148. 'openid'=>$data['openid'],
  149. 'unionid'=>$data['unionid'],
  150. 'distribution_channel_id'=>$user->distribution_channel_id,
  151. 'u'=>$data['u']
  152. ]);
  153. return $user;
  154. }
  155. }
  156. /**
  157. * @apiVersion 1.0.0
  158. * @apiDescription 刷新token
  159. * @api {get} RefreshToken 刷新token
  160. * @apiParam {String} [token] token
  161. * @apiHeader {String} [Authorization] token 两个token任选其一
  162. * @apiGroup Login
  163. * @apiName RefreshToken
  164. * @apiSuccess {int} code 状态码
  165. * @apiSuccess {String} msg 信息
  166. * @apiSuccess {object} data 结果集
  167. * @apiSuccess {String} data.token token
  168. * @apiSuccess {Int} data.time 过期时间
  169. * @apiSuccessExample {json} Success-Response:
  170. * HTTP/1.1 200 OK
  171. * {
  172. * code: 0,
  173. * msg: "",
  174. * data: {
  175. * token:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,
  176. * time:123455
  177. * }
  178. * }
  179. */
  180. public function RefreshToken()
  181. {
  182. try{
  183. $old_token = JWTAuth::getToken();
  184. $token = JWTAuth::refresh($old_token);
  185. $time = time() + 7200;
  186. return response()->success(compact('token', 'time'));
  187. }catch (\Exception $e){
  188. }
  189. return response()->error('XCX_NOT_LOGIN');
  190. }
  191. private function getUserWeixinInfo($js_code)
  192. {
  193. if (empty($js_code)) {
  194. return false;
  195. }
  196. $url = 'https://api.weixin.qq.com/sns/jscode2session?';
  197. $client = new Client([
  198. 'timeout' => 2.0,
  199. ]);
  200. $appid = 'wxa0c8331eba3b34d5';
  201. $secret = '17c01c26dd7873e557710601436774c7';
  202. $grant_type = 'authorization_code';
  203. try {
  204. $res = $client->get($url . http_build_query(compact('js_code', 'appid', 'secret', 'grant_type')))->getBody()->getContents();
  205. Log::info('code 换取 session_key is :');
  206. Log::info($res);
  207. $res = json_decode($res, true);
  208. if (isset($res['errcode'])) {
  209. return false;
  210. }
  211. return $res;
  212. } catch (\Exception $e) {
  213. Log::info($e);
  214. return false;
  215. }
  216. }
  217. /**
  218. * 检验数据的真实性,并且获取解密后的明文.
  219. * @param $encryptedData string 加密的用户数据
  220. * @param $iv string 与用户数据一同返回的初始向量
  221. * @param $data string 解密后的原文
  222. *
  223. * @return int 成功0,失败返回对应的错误码
  224. */
  225. private function decryptData($appid, $sessionKey,$encryptedData, $iv, &$data )
  226. {
  227. if (strlen($sessionKey) != 24) {
  228. return ErrorCode::$IllegalAesKey;
  229. }
  230. $aesKey=base64_decode($sessionKey);
  231. if (strlen($iv) != 24) {
  232. return ErrorCode::$IllegalIv;
  233. }
  234. $aesIV=base64_decode($iv);
  235. $aesCipher=base64_decode($encryptedData);
  236. $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
  237. $dataObj=json_decode( $result );
  238. if( $dataObj == NULL )
  239. {
  240. return ErrorCode::$IllegalBuffer;
  241. }
  242. if( $dataObj->watermark->appid !=$appid )
  243. {
  244. return ErrorCode::$IllegalBuffer;
  245. }
  246. $data = $result;
  247. return ErrorCode::$OK;
  248. }
  249. }
  250. class ErrorCode
  251. {
  252. public static $OK = 0;
  253. public static $IllegalAesKey = -41001;
  254. public static $IllegalIv = -41002;
  255. public static $IllegalBuffer = -41003;
  256. public static $DecodeBase64Error = -41004;
  257. }