MiniProgramLoginForm.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. namespace api\modules\v1\forms;
  3. use Yii;
  4. use yii\base\Model;
  5. /**
  6. * Class MiniProgramLoginForm
  7. * @package api\modules\v1\models
  8. */
  9. class MiniProgramLoginForm extends Model
  10. {
  11. public $iv;
  12. public $rawData;
  13. public $encryptedData;
  14. public $signature;
  15. public $code;
  16. public $auth;
  17. /**
  18. * @var string
  19. */
  20. protected $openid;
  21. /**
  22. * @var string
  23. */
  24. protected $unionid;
  25. /**
  26. * @inheritdoc
  27. */
  28. public function rules()
  29. {
  30. return [
  31. [['iv', 'rawData', 'encryptedData', 'signature', 'code'], 'required'],
  32. [['signature'], 'authVerify'],
  33. ];
  34. }
  35. public function attributeLabels()
  36. {
  37. return [
  38. 'iv' => '加密算法的初始向量',
  39. 'rawData' => '不包括敏感信息的原始数据字符串,用于计算签名',
  40. 'encryptedData' => '包括敏感数据在内的完整用户信息的加密数据',
  41. 'signature' => '签名',
  42. 'code' => 'code码',
  43. 'auth' => '授权秘钥',
  44. ];
  45. }
  46. /**
  47. * @param $attribute
  48. * @throws \EasyWeChat\Kernel\Exceptions\HttpException
  49. * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
  50. * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
  51. * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
  52. * @throws \Psr\SimpleCache\InvalidArgumentException
  53. * @throws \yii\web\UnprocessableEntityHttpException
  54. */
  55. public function authVerify($attribute)
  56. {
  57. $auth = Yii::$app->wechat->miniProgram->auth->session($this->code);
  58. // 解析是否接口报错
  59. Yii::$app->services->base->getWechatError($auth);
  60. $sign = sha1(htmlspecialchars_decode($this->rawData . $auth['session_key']));
  61. if ($sign !== $this->signature) {
  62. $this->addError($attribute, '签名错误');
  63. return;
  64. }
  65. $this->auth = $auth;
  66. $this->openid = $auth['openid'] ?? '';
  67. $this->unionid = $auth['unionid'] ?? '';
  68. }
  69. /**
  70. * @return mixed
  71. */
  72. public function getOpenid()
  73. {
  74. return $this->openid;
  75. }
  76. /**
  77. * @return mixed
  78. */
  79. public function getUnionId()
  80. {
  81. return $this->unionid;
  82. }
  83. /**
  84. * @return array
  85. * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
  86. */
  87. public function getUser()
  88. {
  89. $user = Yii::$app->wechat->miniProgram->encryptor->decryptData($this->auth['session_key'], $this->iv, $this->encryptedData);
  90. !empty($this->openid) && $user['openId'] = $this->openid;
  91. !empty($this->unionid) && $user['unionId'] = $this->unionid;
  92. return $user;
  93. }
  94. }
粤ICP备19079148号