微信小程序登录

小程序端

Page({
  // 点击登录事件
  login:function(event){
    // 调用登录接口
    wx.login({
      success:function (res){
        var code = res.code;  
        console.log(code);
        wx.getUserInfo({
          success:function(info){
            var rawData = info['rawData'];
            var signature = info['signature'];
            var encryptedData = info['encryptedData']; 
            var iv = info['iv'];
            // 发送请求
            wx.request({
              url:'http://www.test.com/api/login/login',
              data:{
                "code": code,
                "rawData": rawData,
                "signature": signature,
                'iv': iv,
                'encryptedData': encryptedData
              },
              success:function(res){
                console.log(res);
              }
            })
          }
        })
      }
    })
  }
})

PHP端_thinkphp5.1

方式一:使用easyWeChat

class Login extends Controller
{
    public function login(Request $request){
        $code = $request->param('code');
        $rawData = $request->param('rawData');
        $signature = $request->param('signature');
        $iv = $request->param('iv');
        $encryptedData = $request->param('encryptedData');

        $config = [
            'app_id' => 'xxxxxxxxxxxxxxxxxxxxx',
            'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxx',
        ];
        $app = Factory::miniProgram($config);
        $value = $app->auth->session($code);
        dump($value);
        // // 获取随机唯一id字符串
        $noncestr = uniqid();

        $rd_session = Session::set($noncestr,$value['session_key'],);
        
        return json($rd_session);
    }
    
}

方式二

class Login extends Controller
{
    public static $app_id = "wx8fee3f5cad70de33";
    public static $secret = "99afc99bb4b08fc5a9825d63ae757a62";

    public function login(Request $request){

        // 获取$code
        $code = $request->param('code');
        $code = '043cdZMH1CgPq40tciLH1RQUMH1cdZM-';

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".self::$app_id."&secret=".self::$secret."&js_code=".$code."&grant_type=authorization_code";

        $this->doCurl($url);
        
        $id = $info['openid'] = @$data->openid;


        return json(['status'=>1]);

    }
    

    public function doCurl($url)
    {
        $curl = curl_init();
        // 使用curl_setopt()设置要获取的URL地址
        curl_setopt($curl,CURLOPT_URL,$url);
        // 设置是否输出header
        curl_setopt($curl,CURLOPT_HEADER,false);
        // 设置是否输出结果
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        // 设置是否检查服务器证书
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        // 使用curl_exec()将CURL返回的结果转换成正常数据并保存到一个变量
        $data = curl_exec($curl);
        // 使用curl_close()关闭curl会话
        curl_close($curl);
        return json_decode($data);
    }
}
杂念太多,必然根基浅薄
原文地址:https://www.cnblogs.com/starshine-zhp/p/12954736.html