panda 1 年之前
父节点
当前提交
b2f3c7af3a

+ 99 - 0
application/api/controller/Passport.php

@@ -0,0 +1,99 @@
+<?php
+
+namespace app\api\controller;
+
+use app\common\controller\Api;
+use app\utils\Easywechat\MiniAppService;
+use think\Cache;
+
+/**
+ * 通行证
+ */
+class Passport extends Api
+{
+    protected $noNeedLogin = ['loginWxMini', 'loginWxMiniPhone'];
+    protected $noNeedRight = '*';
+    protected $model       = null;
+
+    public function _initialize()
+    {
+        parent::_initialize();
+    }
+
+    /**
+     * 微信小程序手机号授权
+     * @return void
+     */
+    public function loginWxMiniPhone()
+    {
+        // 获取参数
+        $params = $this->request->param();
+        if (empty($params['code'])) {
+            $this->error('The code is required.');
+        }
+
+        $wxMiniApp = new MiniAppService();
+        $wx        = $wxMiniApp->getUserPhone($params['code']);
+        if (empty($wx['phone_info']['purePhoneNumber'])) {
+            $this->error('手机号授权失败.', $wx);
+        }
+
+        $mobile = $wx['phone_info']['purePhoneNumber'];
+        $extend = [];
+        if (!empty($params['openid']) && $wxInfo = Cache::get($params['openid'])){
+            $extend['mini_openid'] = $wxInfo['openid'] ?? '';
+            $extend['mini_sessionkey'] = $wxInfo['session_key'] ?? '';
+        }
+
+        // 校验手机号登录信息
+        list($exists, $user_id) = UserModel::checkExists('', $mobile);
+        if (!$exists) {
+            // 手机号不存在 创建账号
+            $ret = $this->auth->register('1', '1', '', $mobile, $extend);
+            if (!$ret) {
+                $this->error("注册失败!");
+            }
+            $user_id = $this->auth->id;
+        }
+
+        // 写入登录Cookies和Token
+        if (!$this->auth->direct($user_id,$extend)) {
+            $this->error($this->auth->getError());
+        }
+        $userInfo = $this->auth->getUserinfo();
+        $result   = [
+            'token' => $userInfo['token'],
+//            'userInfo' => $userInfo
+        ];
+        $this->success('登录成功', $result);
+    }
+
+    /**
+     * 微信小程序授权
+     *
+     * @return void
+     */
+    public function loginWxMini()
+    {
+        // 获取参数
+        $params = $this->request->param();
+        if (empty($params['code'])) {
+            $this->error('The code is required.');
+        }
+
+        $wxMiniApp = new MiniAppService();
+        $res       = $wxMiniApp->login($params['code']);
+
+        if (empty($res['openid'])) {
+            $this->error('授权失败,请重试');
+        }
+
+        $sign = md5($res['openid']);
+
+        Cache::set($sign, $res, 3600);
+
+        $this->success('success', [
+            'openid' => $sign
+        ]);
+    }
+}

+ 5 - 0
application/config.php

@@ -298,6 +298,11 @@ return [
         //API接口地址
         //API接口地址
         'api_url'               => 'https://api.fastadmin.net',
         'api_url'               => 'https://api.fastadmin.net',
     ],
     ],
+    //用户端小程序
+    'user_wxMiniProgram' => [
+        'appid' => 'wx29d6281c5252f504',
+        'secret' => '915adfd0f51bb9c67fb9f9dfd94a101b'
+    ],
     // 腾讯im配置
     // 腾讯im配置
     'tencent_im' => [
     'tencent_im' => [
 //        'sdkappid' => '1400589001',
 //        'sdkappid' => '1400589001',

+ 9 - 4
application/index/controller/Index.php

@@ -4,6 +4,7 @@ namespace app\index\controller;
 
 
 use app\common\controller\Frontend;
 use app\common\controller\Frontend;
 use app\utils\PayUtil;
 use app\utils\PayUtil;
+use think\Cache;
 use think\Db;
 use think\Db;
 class Index extends Frontend
 class Index extends Frontend
 {
 {
@@ -16,14 +17,18 @@ class Index extends Frontend
     /**
     /**
      * 测试 汇付 支付
      * 测试 汇付 支付
      */
      */
-    public function aa()
+    public function testPay()
     {
     {
         $params = \request()->post();
         $params = \request()->post();
-        $openid = $params['openid'] ?? '';
         $order_no = $params['order_no'] ?? '';
         $order_no = $params['order_no'] ?? '';
+
+        $wxInfo = Cache::get($params['openid'] ?? '');
+        $openid = $wxInfo['openid'] ?? '';
+//        $sessionKey = $wxInfo['session_key'] ?? '';
+
         $pay = new PayUtil();
         $pay = new PayUtil();
-        $order_no = !empty($order_no) ? $order_no : time().rand(1,200);
-        $pay->jsPay($openid,"D0{$order_no}",'0.01','开通会员');
+        $order_no = !empty($order_no) ? $order_no : time() . rand(1, 200);
+        $pay->jsPay($openid, "D0{$order_no}", '0.01', '开通会员');
         return json_encode([
         return json_encode([
             'order_no' => $order_no,
             'order_no' => $order_no,
             'data' => $pay->getData()
             'data' => $pay->getData()

+ 92 - 0
application/utils/Easywechat/MiniAppService.php

@@ -0,0 +1,92 @@
+<?php
+
+namespace app\utils\Easywechat;
+
+use app\utils\CurlUtil;
+
+/**
+ * Author:Panda
+ * Email:joeyoung0314@qq.com
+ * Class MiniAppService
+ * @package App\Service\Easywechat
+ */
+class MiniAppService
+{
+    private $config;
+    private $domain = 'https://api.weixin.qq.com';// 微信接口地址前缀
+
+
+    public function __construct()
+    {
+        $this->config = config('user_wxMiniProgram');
+    }
+
+    /**
+     * 获取openid && session_key
+     * @param string $code
+     * @return mixed
+     */
+    public function login(string $code)
+    {
+        $config = $this->config;
+
+        $response = $this->get('/sns/jscode2session', [
+            'appid'      => $config['appid'],
+            'secret'     => $config['secret'],
+            'js_code'    => $code,
+            'grant_type' => 'authorization_code',
+        ]);
+
+        return $this->json($response);
+    }
+
+    /**
+     * 获取手机号
+     * @param string $code
+     * @return false|mixed
+     */
+    public function getUserPhone(string $code)
+    {
+        $access_token = $this->accessToken();
+        if (empty($access_token['access_token'])){
+            return $access_token;
+        }
+
+        $response = $this->postJson("/wxa/business/getuserphonenumber?access_token={$access_token['access_token']}", [
+            'code'    => $code
+        ]);
+
+        return $this->json($response);
+    }
+
+    /**
+     * 获取 access_token
+     * @return false|mixed
+     */
+    private function accessToken()
+    {
+        $config = $this->config;
+
+        $response = $this->postJson('/cgi-bin/stable_token', [
+            'grant_type'    => 'client_credential',
+            'appid'         => $config['appid'],
+            'secret'        => $config['secret'],
+            'force_refresh' => false,// 默认false:普通模式false;强制刷新模式true;
+        ]);
+
+        return $this->json($response);
+    }
+
+    public function json($response)
+    {
+        return json_decode($response, true);
+    }
+
+    private function postJson(string $uri,array $params = []){
+        return CurlUtil::post($this->domain.$uri,json_encode($params));
+    }
+
+    private function get(string $uri,array $params = []){
+        return CurlUtil::get($this->domain.$uri,$params);
+    }
+}