PlatformLoginForm.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. namespace app\modules\client\models\v1;
  8. use app\models\Option;
  9. use app\models\SaasUser;
  10. use app\models\User;
  11. use app\models\WechatConfig;
  12. use app\modules\client\models\ApiModel;
  13. use EasyWeChat\Factory;
  14. use Think\Model;
  15. class PlatformLoginForm extends ApiModel
  16. {
  17. public $store_id;
  18. public $phone;
  19. // 微信小程序
  20. public $code;
  21. public $encryptedData;
  22. public $iv;
  23. public function rules()
  24. {
  25. return [
  26. [['code', 'encryptedData', 'iv', 'phone'], 'string'],
  27. [['code', 'encryptedData', 'iv'], 'trim'],
  28. [['store_id'], 'integer'],
  29. ];
  30. }
  31. public function login() {
  32. if (!$this->validate()) {
  33. return [
  34. 'code' => 1,
  35. 'msg' => $this->getErrorSummary(false)[0],
  36. ];
  37. }
  38. // 获取平台微信配置进行初始化
  39. $wechat_config = Option::getSaasWechat();
  40. // $config = [
  41. // 'app_id' => $wechat_config['sp_appid'],
  42. // 'secret' => $wechat_config['sp_key'],
  43. // 'response_type' => 'array'
  44. // ];
  45. $config = [
  46. 'app_id' => 'wx44a1c390fb6fbfdd',
  47. 'secret' => 'b39f12cac61ad5bf63506058752d5f49',
  48. 'response_type' => 'array'
  49. ];
  50. \Yii::error($config);
  51. $wechat = Factory::miniProgram($config);
  52. if (!$wechat) {
  53. throw new \Exception('Wechat App Is Null', 1);
  54. }
  55. $session = $wechat->auth->session($this->code);
  56. if (!$session || empty($session['openid'])) {
  57. throw new \Exception('获取openid失败.');
  58. }
  59. $saas_user = SaasUser::findOne(['mobile' => $this->phone]);
  60. if (!$saas_user) {
  61. $saas_user = new SaasUser();
  62. $saas_user->store_id = $this->store_id;
  63. $saas_user->mobile = $this->phone;
  64. $saas_user->platform_open_id = $session['openid'];
  65. } else {
  66. $saas_user->platform_open_id = $session['openid'];
  67. }
  68. if (!$saas_user->save()) {
  69. return [
  70. 'code' => 1,
  71. 'msg' => $saas_user->errors[0]
  72. ];
  73. }
  74. return [
  75. 'code' => 0,
  76. 'msg' => 'success'
  77. ];
  78. }
  79. }