Explorar o código

提现和微信登录

zhangxiaobin hai 1 ano
pai
achega
6e64514c1c

+ 107 - 37
application/api/controller/User.php

@@ -5,6 +5,7 @@ namespace app\api\controller;
 use app\common\controller\Api;
 use app\common\library\Ems;
 use app\common\library\Sms;
+use app\common\library\Wechat;
 use app\common\service\UserService;
 use fast\Random;
 use think\Exception;
@@ -712,55 +713,42 @@ class User extends Api
 
     //微信登录
     public function wechatlogin(){
-//        $nickname = input('nickname','');
-//        $avatar = input('avatar','');
-        $gender = input('gender',1);
-        $wechat_openid = input('openid','');
 
-        if (!$wechat_openid) {
+        $code = input_post('code','');
+        if(!$code){
             $this->error(__('Invalid parameters'));
         }
-//        if($gender != 1){
-//            $gender = 0;
-//        }
+        //微信
+        $wechat = new Wechat();
+
+        $wxuserinfo = $wechat->getwxuserinfo($code);
+        if(!$wxuserinfo){
+            $this->error('openid获取失败');
+        }
+        $openid = $wxuserinfo['openid'];
 
-        $user = \app\common\model\User::getByOpenid($wechat_openid);
+        $user = Db::name('user')->where('openid',$openid)->find();
         if ($user) {
-            if ($user->status != 1) {
-                $this->error(__('Account is locked'));
+            if ($user['status'] == 2) {
+                $this->error(__('Account is log off'));
             }
-            if ($user->frozentime > time()) {
-                $this->error('您的账号已被封禁至' . date('Y-m-d H:i'));
+            if ($user['status'] != 1) {
+                $this->error(__('Account is locked'));
             }
             //如果已经有账号则直接登录
-            $ret = $this->auth->direct($user->id);
-
-            //非首次注册男性用户每次打开app,系统自动推送女性(公会)打招呼消息3人次
-            /*if($user->gender == 1 && $user->gh_id == 0){
-                $this->firstopen_send($user->id);
-            }*/
+            $ret = $this->auth->direct($user['id']);
+            $is_register = 0;
         } else {
-//            $this->success('选择性别', ['code' => 5]);
-
-//            if (!$nickname || !$avatar) {
-//                $this->error(__('Invalid parameters'));
-//            }
-
-            $reg_data = [
-//                'nickname'=>$nickname,
-//                'avatar'=>$avatar,
-//                'gender'=>$gender,
-                'register_from' => input('register_from',''),
-                'gender' => $gender,
+            $extend = [
+                'openid' => $openid,
             ];
-            $ret = $this->auth->openid_register($wechat_openid,$reg_data);
-            //亿米
-            /*if(input('register_from','') == 'xiaomi'){
-                $this->yimi_advert();
-            }*/
+            $mobile = '';
+            $ret = $this->auth->register($mobile, Random::alnum(), $mobile, $extend);
+            $is_register = 1;
+            //$ret = $this->auth->openid_register($openid,$extend);
         }
         if ($ret) {
-            $data = ['userinfo' => $this->auth->getUserinfo()];
+            $data = ['is_register' => $is_register, 'userinfo' => $this->auth->getUserinfo()];
             $this->success(__('Logged in successful'), $data);
         } else {
             $this->error($this->auth->getError());
@@ -1124,4 +1112,86 @@ class User extends Api
         Db::commit();
         $this->success($msg);
     }
+
+    /**
+     * 微信注册来的,绑定手机号
+     *
+     * @ApiMethod (POST)
+     * @param string $mobile   手机号
+     * @param string $captcha 验证码
+     */
+    public function bindmobile()
+    {
+        $user = $this->auth->getUser();
+        $mobile = $this->request->post('mobile');
+        $captcha = $this->request->post('captcha');
+
+        if(!empty($this->auth->mobile)){
+            $this->error('已经绑定了手机号');
+        }
+        if (!$mobile || !$captcha) {
+            $this->error(__('Invalid parameters'));
+        }
+        if (!Validate::regex($mobile, "^1\d{10}$")) {
+            $this->error(__('Mobile is incorrect'));
+        }
+        if (\app\common\model\User::where('mobile', $mobile)->find()) {
+            $this->error('该手机号已被其他用户绑定');
+        }
+        $result = Sms::check($mobile, $captcha, 'changemobile');
+        if (!$result) {
+            $this->error(__('Captcha is incorrect'));
+        }
+        $verification = $user->verification;
+        $verification->mobile = 1;
+        $user->verification = $verification;
+        $user->mobile = $mobile;
+        $user->save();
+
+        Sms::flush($mobile, 'changemobile');
+        $this->success('success',$this->userInfo('return'));
+    }
+
+    /**
+     * 手机注册来的,绑定微信
+     *
+     * @ApiMethod (POST)
+     * @param string $wechat_openid
+     */
+    public function bindopenid()
+    {
+        $code = input_post('code','');
+        if(!$code){
+            $this->error(__('Invalid parameters'));
+        }
+        //微信
+        $wechat = new Wechat();
+        $openid = $wechat->getOpenid($code);
+        if(!$openid){
+            $this->error('openid获取失败');
+        }
+
+        $user = $this->auth->getUser();
+        if(!empty($this->auth->openid)){
+            $this->error('已经绑定了微信号');
+        }
+
+        if (\app\common\model\User::where('openid', $openid)->find()) {
+            $this->error('该微信号已被其他用户绑定');
+        }
+
+        $user->openid = $openid;
+        $user->save();
+
+        $this->success('success',$this->userInfo('return'));
+    }
+
+    //用户详细资料
+    public function userInfo($type = 1){
+        $info = $this->auth->getUserinfo();
+        if($type == 'return'){
+            return $info;
+        }
+        $this->success(__('success'),$info);
+    }
 }

+ 5 - 3
application/api/controller/Usercenter.php

@@ -1300,6 +1300,7 @@ class UserCenter extends Common
                 if ($money <= 0) {
                     throw new Exception('金额有误');
                 }
+                $inputMoney = $money;
                 $moneys = bcmul($money,$withdrawRate,2);
                 $platformMoney = bcsub($money,$moneys,2);
             } else {//提现配置
@@ -1308,6 +1309,7 @@ class UserCenter extends Common
                 if (empty($withdrawalConfig)) {
                     throw new Exception('未知的配置信息');
                 }
+                $inputMoney = $withdrawalConfig['money'];
                 $moneys = $withdrawalConfig['money'];
                 $platformMoney = bcsub($moneys,$withdrawalConfig['real_money'],2);;
             }
@@ -1315,7 +1317,7 @@ class UserCenter extends Common
                 throw new Exception('申请金额异常');
             }
             //扣减余额 记录余额日志
-            $walletRes = model('wallet')->lockChangeAccountRemain($userId, $moneys, '-', $userMoney, '申请提现', 104,'money');
+            $walletRes = model('wallet')->lockChangeAccountRemain($userId, $inputMoney, '-', $userMoney, '申请提现', 104,'money');
             if (!$walletRes['status']) {
                 throw new Exception($walletRes['msg']);
             }
@@ -1342,9 +1344,9 @@ class UserCenter extends Common
             }
             $data = [
                 'user_id'       => $userId,//用户ID
-                'money'         => $moneys,//金额
+                'money'         => $inputMoney,//金额
                 'handingfee'    => $platformMoney,//手续费
-                'real_money'    => bcsub($moneys,$platformMoney,2),//金额
+                'real_money'    => bcsub($inputMoney,$platformMoney,2),//金额
                 'taxes'         => 0.00,//税费
                 'type'          => $typeStr,//类型
                 'account'       => $account,//提现账户

+ 14 - 4
application/common/library/Auth.php

@@ -159,9 +159,16 @@ class Auth
 //            $this->setError('Nickname already exist');
 //            return false;
 //        }
-        if ($mobile && User::getByMobile($mobile)) {
-            $this->setError('Mobile already exist');
-            return false;
+        if (!isset($extend['openid'])) {
+            if (!empty($extend['openid']) && User::getByOpenid($extend['openid'])) {
+                $this->setError('微信账号已存在');
+                return false;
+            }
+        } else {
+            if ($mobile && User::getByMobile($mobile)) {
+                $this->setError('Mobile already exist');
+                return false;
+            }
         }
 
         $ids = User::column("u_id");
@@ -185,6 +192,9 @@ class Auth
             'image'     => '/assets/img/default_avatar.png',
             //'desc'      => '这个人很懒,什么都没留下~',
         ];
+        if (isset($extend['openid']) && !empty($extend['openid'])) {
+            $data['openid']  = $extend['openid'];
+        }
         //https://bansheng-1304213176.cos.ap-guangzhou.myqcloud.com/
         $params = array_merge($data, [
             'nickname' => "gg_" . $data["u_id"],
@@ -780,7 +790,7 @@ class Auth
         $introcode = User::column("invite_no");
 
         $data = [
-            'wechat_openid'   => $wechat_openid,
+            'openid'   => $wechat_openid,
             'gender'   => isset($extend['gender']) ? $extend['gender'] : 1,
             'avatar' => isset($extend["avatar"]) ? $extend["avatar"] : '/assets/dc0f37f043e1e9f5240ed87e37f18740.png',
             'invite_no' => $this->getUinqueNo(6, $introcode),

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

@@ -0,0 +1,174 @@
+<?php
+
+namespace app\common\library;
+
+use fast\Http;
+use think\Cache;
+use think\Session;
+
+/**
+ * 微信授权
+ *
+ */
+class Wechat
+{
+    private $app_id = config('wxMiniProgram')['appid'];
+    private $app_secret = config('wxMiniProgram')['secret'];
+
+    private $scope = 'snsapi_userinfo';
+
+    /*public function __construct($app_id, $app_secret)
+    {
+        $this->app_id = $app_id;
+        $this->app_secret = $app_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) {
+            /*if (!isset($_REQUEST['code'])) {
+                return '';
+            } else {
+                $code = $_REQUEST['code'];*/
+                $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;
+    }
+}