微信小程序登录以及获取openid(用户唯一标识)和session_key

一、前端登录代码:

 //登录获取code  login:function(){    wx.login({      success:function(res){        console.log(res.code)        //发送请求        wx.request({          url: '填写你的后端接口地址', //接口地址          data: {code:res.code},          header: {            'content-type': 'application/json' //默认值          },          success: function (res) {            console.log(res.data)          }        })      }    })  }

二、后端接收code,获取openid和session_key

/** * 登录 */public function login(){$code = $_GET['code'];$appid = '修改成你小程序的APPID';$AppSecret = '修改成你小程序的APPSECRET';$url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$AppSecret."&js_code=".$code."&grant_type=authorization_code";        $str = file_get_contents($url);        $json = json_decode($str);        $arr = get_object_vars($json);    echo $openid = $arr['openid']; //这是openid    echo '/br';    echo $session_key = $arr['session_key']; //这是session_key}

三、这样你就获取到你需要的openid了,最好获取到openid以后存进数据库,避免重复获取

四、谢谢,再见

TAG标签: 微信小程序php小程序

http://www.xiaochengxub.com/read-104329.html