Browse Source

微信注册

lizhen_gitee 8 months ago
parent
commit
999338a57e
2 changed files with 308 additions and 2 deletions
  1. 137 2
      application/api/controller/User.php
  2. 171 0
      application/common/library/Wechat.php

+ 137 - 2
application/api/controller/User.php

@@ -15,7 +15,7 @@ use app\common\model\UserDeviceInfo;
 use onlogin\onlogin;
 
 use addons\epay\library\Service;
-use addons\epay\library\Wechat;
+use app\common\library\Wechat;
 
 use TencentCloud\Common\Credential;
 use TencentCloud\Common\Profile\ClientProfile;
@@ -235,7 +235,7 @@ class User extends Api
         }
     }
 
- 
+
 
     /**
      * 运营商一键登录
@@ -422,6 +422,141 @@ class User extends Api
         $this->success(__('success'),$info);
     }
 
+
+    //微信登录,预先假注册
+    public function wechatlogin(){
+        $code = input('code','');
+        if(!$code){
+            $this->error(__('Invalid parameters'));
+        }
+        //微信
+        $wechat = new Wechat();
+        $wxuserinfo = $wechat->getAccessToken($code);
+
+        if(!$wxuserinfo){
+            $this->error('openid获取失败');
+        }
+        if(!is_array($wxuserinfo) || !isset($wxuserinfo['openid'])){
+            $this->error('openid获取失败');
+        }
+
+        $openid = $wxuserinfo['openid'];
+
+        //检查用户
+        $user = Db::name('user')->where('wechat_openid',$openid)->find();
+        if ($user) {
+            if ($user['status'] == -1) {
+                $this->error('账户已注销');
+            }
+            if ($user['status'] != 1) {
+                $this->error(__('Account is locked'));
+            }
+            //如果已经有账号则直接登录
+            $ret = $this->auth->direct($user['id']);
+
+            if ($ret) {
+                $userInfo = $this->auth->getUserinfo();
+                $userInfo['is_register'] = 0;
+                $userInfo['code'] = $code;
+                $this->success(__('Logged in successful'), $userInfo);
+            } else {
+                $this->error($this->auth->getError());
+            }
+
+        } else {
+            //记录code和openid,绑定手机号的时候更新openid
+            $wechatCodeData = [
+                'code' => $code,
+                'openid' => $openid,
+                'createtime' => time(),
+            ];
+            $wechatCode = Db::name('wechat_code')->where(['openid'=>$openid])->find();
+            if (empty($wechatCode)) {
+                Db::name('wechat_code')->insertGetId($wechatCodeData);
+            } else {
+                Db::name('wechat_code')->where(['openid'=>$openid])->update($wechatCodeData);
+            }
+
+            //直接返回
+            $userInfo = [];
+            $userInfo['is_register'] = 1;
+            $userInfo['code'] = $code;
+            $this->success('获取信息成功', $userInfo);
+        }
+
+    }
+
+    /**
+     * 微信注册来的,绑定手机号
+     *
+     * @ApiMethod (POST)
+     * @param string $mobile   手机号
+     * @param string $captcha 验证码
+     */
+    public function wechatbindmobile()
+    {
+        $mobile = $this->request->param('mobile');
+        $captcha = $this->request->param('captcha');
+        $code = $this->request->param('code');
+
+        if (!$mobile || !$captcha || !$code) {
+            $this->error(__('Invalid parameters'));
+        }
+        if (!Validate::regex($mobile, "^1\d{10}$")) {
+            $this->error(__('Mobile is incorrect'));
+        }
+        $result = Sms::check($mobile, $captcha, 'changemobile');
+        if (!$result) {
+            $this->error(__('Captcha is incorrect'));
+        }
+
+        $wechatCodeWhere['code'] = $code;
+        $wechatCode = Db::name('wechat_code')->where($wechatCodeWhere)->find();
+        if (empty($wechatCode)) {
+            $this->error('请先微信登录');
+        }
+
+        //检查appid绑定的用户
+        $user = Db::name('user')->where('wechat_openid',$wechatCode['openid'])->find();
+        if ($user) {
+            if ($user['status'] == -1) {
+                $this->error('账户已注销');
+            }
+            if ($user['status'] != 1) {
+                $this->error(__('Account is locked'));
+            }
+            //如果已经有账号则直接登录
+            $ret = $this->auth->direct($user['id']);
+            $this->success('success',$this->userInfo('return'));
+        }
+
+        //新的openid用户
+        $where = [];
+        $where['mobile'] = $mobile;
+        $userData = Db::name('user')->where($where)->find();//老用户
+        if (!empty($userData)) {
+            if (empty($userData['wechat_openid'])) {
+                Db::name('user')->where('id',$userData['id'])->update(['wechat_openid' => $wechatCode['openid']]);//老用户更新openid
+            } else {
+                if ($userData['wechat_openid'] != $wechatCode['openid']) {
+                    $this->error('该手机号已被其他用户绑定');
+                }
+            }
+            $ret = $this->auth->direct($userData['id']);
+        } else {
+            $extend = [
+                'wechat_openid' => $wechatCode['openid'],
+            ];
+            $ret = $this->auth->register('', '','', $mobile, $extend);
+        }
+        if (!$ret) {
+            $this->error($this->auth->getError());
+        }
+
+        $this->success('success',$this->userInfo('return'));
+
+    }
+
  
 
     public function testhaibao(){

+ 171 - 0
application/common/library/Wechat.php

@@ -0,0 +1,171 @@
+<?php
+
+namespace app\common\library;
+
+use fast\Http;
+use think\Cache;
+use think\Session;
+
+/**
+ * 微信授权
+ *
+ */
+class Wechat
+{
+    private $app_id = '';
+    private $app_secret = '';
+
+    private $scope = 'snsapi_userinfo';
+
+    public function __construct()
+    {
+        $wxConfig = config('user_wxMiniProgram');
+        $this->app_id = $wxConfig['appid'];
+        $this->app_secret = $wxConfig['secret'];
+    }
+
+    /**
+     * 获取微信授权链接
+     *
+     * @return string
+     */
+    /*public function getAuthorizeUrl()
+    {
+        $redirect_uri = addon_url('epay/api/wechat', [], true, true);
+        $redirect_uri = urlencode($redirect_uri);
+        $state = \fast\Random::alnum();
+        Session::set('state', $state);
+        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code&scope={$this->scope}&state={$state}#wechat_redirect";
+    }*/
+
+    /**
+     * 获取微信openid
+     *
+     * @return mixed|string
+     */
+
+    /*
+     array(5) {
+                  ["access_token"] => string(89) "49_r4I-StVANS8uYWTUHG86GJ-g1iH6mMFWy-9LeOta--2l6Bzg8LVDQFu8VSARu87atETzVJFZ-fndy-aQqEb8wQ"
+                  ["expires_in"] => int(7200)
+                  ["refresh_token"] => string(89) "49_8Vfa-imGcRmUwcESvpvMcEkiuh8kmD_movl9bIz9DV5GonZrqfIya5NgT7G-NMeJ7KTuCjMrSJi4BtojjDxnCQ"
+                  ["openid"] => string(28) "o8lxjwRjlDortQKhTk1dpHjQxcBU"
+                  ["scope"] => string(15) "snsapi_userinfo"
+            }
+     * */
+
+    public function getOpenid($code = '')
+    {
+        $openid = Session::get('openid');
+        if (!$openid) {
+
+            $token = $this->getAccessToken($code);
+            $openid = isset($token['openid']) ? $token['openid'] : '';
+            if ($openid) {
+                Session::set("openid", $openid);
+            }
+        }
+        return $openid;
+    }
+
+    /*
+    array(2) {
+              ["ret"] => bool(true)
+              ["msg"] => string(307) "{"openid":"o8lxjwRjlDortQKhTk1dpHjQxcBU","nickname":"科","sex":1,"language":"zh_CN","city":"临沂","province":"山东","country":"中国","headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/LGYWIv4F5vxZ2zCM9GEUynoQeJ6ibX9IfoKPAWLlGIugn1mgaAMPuqxzPBDQ3ktLEv2ia7HmOeJYTg5LofG8YlwQ\/132","privilege":[]}"
+            }
+     */
+    public function getwxuserinfo($code = '')
+    {
+        $wxuserinfo = Session::get('wxuserinfo');
+        if (!$wxuserinfo) {
+
+            $token = $this->getAccessToken($code);
+
+            $openid = isset($token['openid']) ? $token['openid'] : '';
+
+            $access_token = isset($token['access_token']) ? $token['access_token'] : '';
+
+            $ret = Http::sendRequest('https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN');
+            if ($ret['ret']) {
+                $wxuserinfo = json_decode($ret['msg'], true);
+                Session::set('wxuserinfo', $wxuserinfo);
+            }else{
+                $wxuserinfo = [];
+            }
+
+        }
+        return $wxuserinfo;
+    }
+
+
+    /**
+     * 获取授权token网页授权
+     *
+     * @param string $code
+     * @return mixed|string
+     */
+    public function getAccessToken($code = '')
+    {
+        $params = [
+            'appid'      => $this->app_id,
+            'secret'     => $this->app_secret,
+            'code'       => $code,
+            'grant_type' => 'authorization_code'
+        ];
+        $ret = Http::sendRequest('https://api.weixin.qq.com/sns/oauth2/access_token', $params, 'GET');
+        if ($ret['ret']) {
+            $ar = json_decode($ret['msg'], true);
+            return $ar;
+        }
+        return [];
+    }
+
+   /* public function getPublicAccessToken(){
+        $ret = Http::sendRequest('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->app_id.'&secret='.$this->app_secret);
+
+        if ($ret['ret']) {
+            $ar = json_decode($ret['msg'], true);
+
+            return $ar['access_token'];
+        }
+    }*/
+
+    //{"errcode":0,"errmsg":"ok","msgid":2054095443608862720}
+    /*public function send($ac,$openid,$first,$keyword1,$keyword2,$keyword3,$remark,$color){
+
+        $params = [
+            "touser"     => $openid,
+            "template_id"       => "lEUyDmLgwIaFDi9SNlIosXe-4fD43SiqSOZigIPOfJ8",
+            'url' => 'https://yanglaoweb.lanmaonet.com',
+            "data" => [
+                "first" => ["value"=>$first,"color"=>$color],
+                "keyword1" => ["value"=>$keyword1,"color"=>"#173177"],
+                "keyword2" => ["value"=>$keyword2,"color"=>"#173177"],
+                "keyword3" => ["value"=>$keyword3,"color"=>"#173177"],
+                "remark" => ["value"=>$remark,"color"=>$color],
+            ],
+            'miniprogram' => [],
+        ];
+
+        $rest = curl_post('https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$ac,json_encode($params));
+
+    }*/
+
+    /*public function getJsticket($code = '')
+    {
+        $jsticket = Session::get('jsticket');
+        if (!$jsticket) {
+            $token = $this->getAccessToken($code);
+            $params = [
+                'access_token' => 'token',
+                'type'         => 'jsapi',
+            ];
+            $ret = Http::sendRequest('https://api.weixin.qq.com/cgi-bin/ticket/getticket', $params, 'GET');
+            if ($ret['ret']) {
+                $ar = json_decode($ret['msg'], true);
+                return $ar;
+            }
+        }
+        return $jsticket;
+    }*/
+}