微信小程序wx.login()获取openid,附:前端+后端代码

微信小程序开放了微信登录的api,无论是个人还是企业申请的小程序均可使用。

首先创建一个项目,把这些代码都清空,我们自己写!

clipboard.png

然后,开始写了!
首先index.wxml,写一个button用于发起登录

index.wxml

<!--index.wxml-->
<button bindtap='login'>登录</button>

然后写index.js

通过wx.login()来获取code
如果成功获取,那么返回code
然后调用wx.request()向服务端发起一个请求,即向登录api接口发送code
换取openid和session_key

api接口:

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=APPSECRET&js_code=CODE&grant_type=authorization_code
//index.js
//获取应用实例
const app = getApp()
Page({
  data: {
    
  },
  //登录获取code
  login:function(){
    wx.login({
      success:function(res){
        console.log(res.code)
        //发送请求
        wx.request({
          url: 'test.php', //接口地址
          data: {code:res.code},
          header: {
            'content-type': 'application/json' //默认值
          },
          success: function (res) {
            console.log(res.data)
          }
        })
      }
    })
  }
})

app.js,这个清空,留下这样就行了

//app.js
App({
 
})

那么到这里,小程序端已经搞定了。
开始写服务端,也很容易。

首先获取从小程序传过来的code
再配置自己小程序的appid和appscret
把这些参数拼接到api接口上进行请求发送就可以返回openid和session_key

<?php
//声明CODE,获取小程序传过来的CODE
$code = $_GET["code"];
//配置appid
$appid = "修改成你小程序的APPID";
//配置appscret
$secret = "修改成你小程序的APPSECRET";
//api接口
$api = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
//获取GET请求
function httpGet($url){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
    curl_setopt($curl, CURLOPT_URL, $url);
    $res = curl_exec($curl);
    curl_close($curl);
    return $res;
}
//发送
$str = httpGet($api);
echo $str;
?>

OK完成!把服务端上传到服务器,换到上面的这里

clipboard.png

然后就可以再控制台打印出openid和session_key了

clipboard.png

获取到了,你想怎么玩就怎么玩!后面可以通过wx.getUserinfo获取用户基本信息(头像,昵称,城市,个性签名等相关信息)

作者:tanking

猜你喜欢

转载自www.cnblogs.com/10manongit/p/12711273.html