php获取微信小程序oppenid 代码

1.微信小程序代码

WXML代码

<!--index.wxml-->
<view class="container">
  <view class="userinfo">
    <button open-type="getUserInfo" bindgetuserinfo="getUserInfo">头像授权登录</button>
    <button open-type="getPhoneNumber" style="margin-top:100rpx" bindgetphonenumber="getPhoneNumber">手机授权</button>
  </view>
</view>

js代码(wx.login直接获取code传到后端)

 getUserInfo: function ({ detail }) {
    var that = this;
    wx.login({
      success: async (res) => {
        wx.request({
          url: '后端地址',
          method: 'GET',
          data: {
            code: res.code,
            encryptedData: detail.encryptedData,
            iv: detail.iv
          },
          success: function (data) {
            console.log(data);(后端直接返回openid)
          }
        })
      }
    })
  }

2.php后端代码 返回openid

public function get_api_data($code)
    {
        $appid  =  "wx0653ba0a3274d3b9" ;
        $secret =   "c6afb23611047cbf7d9b4f8799d219ef";
        $URL = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $apiData=file_get_contents($URL);
        return json_decode($apiData,true);
    }

猜你喜欢

转载自blog.csdn.net/chenabin_/article/details/85068050