UsersController.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace App\Http\Controllers\WapAlipay\Oauth;
  3. use Illuminate\Http\Request;
  4. use App\Http\Controllers\Controller;
  5. use Cookie;
  6. use App\Modules\User\Services\UserService;
  7. use Log;
  8. use DB;
  9. use GuzzleHttp\Client;
  10. class UsersController extends Controller
  11. {
  12. /**
  13. * 微信授权回掉
  14. * @param Request $request
  15. * @return \Illuminate\Http\RedirectResponse
  16. */
  17. public function Aliback(Request $request,$distribution_channel_id)
  18. {
  19. if(!is_numeric($distribution_channel_id)){
  20. $distribution_channel_id = decodeDistributionChannelId($distribution_channel_id);
  21. }
  22. $url = Cookie::get('auth_redirect');
  23. //auth_code、app_id、scope
  24. $auth_code = $request->get('auth_code');
  25. $app_id = $request->get('app_id');
  26. $scope = $request->get('scope');
  27. return redirect()->to(urldecode($url));
  28. }
  29. /**
  30. * 授权用户信息
  31. * @param $data
  32. * @return bool
  33. */
  34. protected function createUser($data)
  35. {
  36. if (empty($data['unionid']) || empty($data['openid'])) return false;
  37. $user = UserService::getUserByUnionAndChannelId($data['openid'],$data['distribution_channel_id']);
  38. if ($user) return $user;
  39. return UserService::addUser(
  40. ['openid' => $data['openid'],
  41. 'unionid' => $data['unionid'],
  42. 'distribution_channel_id' => $data['distribution_channel_id'],
  43. 'send_order_id'=>$data['send_order_id'],
  44. 'is_new'=>1
  45. ]);
  46. }
  47. /**
  48. *使用auth_code换取接口access_token及用户userId
  49. * @param string $auth_code
  50. * @return string
  51. */
  52. private function authToUserInfo(string $auth_code):string{
  53. $client = new Client([
  54. 'timeout' => 3,
  55. ]);
  56. $res = null;
  57. try{
  58. $res = $client->request('POST','https://openapi.alipay.com/gateway.do',[
  59. 'form_params'=>[
  60. 'grant_type'=>'authorization_code',
  61. 'code'=>$auth_code
  62. ]
  63. ])->getBody()->getContents();
  64. }catch (\Exception $e){
  65. return '';
  66. }
  67. if(empty($res)){
  68. return '';
  69. }
  70. $res = json_decode($res,1);
  71. if(isset($res['alipay_system_oauth_token_response'])){
  72. return $res['alipay_system_oauth_token_response']['user_id'];
  73. }
  74. return '';
  75. }
  76. }