小程序+php获取用户openid

 获取的用户的唯一标识openid

思路:

        获取openid需要首先使用wx.login()获取登录凭证code,使用code发送wx.request()的get请求,携带参数appid,secret,code给php,php使用file_get_contents()获取返回信息,进而将openid和session_key返回数据给小程序;

返回结果:

小程序示例wxml代码:

给button按钮绑定一个点击事件,view内显示获取成功后的数据(当前只展示openid);

<!-- wxml -->
<button type="primary" bindtap="bindViewTap">获取openid</button>
<view style="height: 80px;width: 750rpx;line-height: 80px;">
    获取openid:{{openid}}
</view>

小程序的js代码:

点击事件先执行login()获取code凭证,然后调用requestCode()并传递获取的用户凭证,发送到自己的php后台进行下一步的处理,不设置method,默认发送get请求;

pages({
    data: {
        phone: '',
        openid: '',
      },

    // 获取code凭证
      bindViewTap() {
        wx.login({
          success: (res) => {
            // 调用requestCode() 传递code凭证
            this.requestCode()(res.code);
          },
        })
      },

      // 接收code凭证,获取手机号
      requestCode()(code) {
        wx.request({
          url: `https://xxx.xxx/getphone.php?openid_code=${code}`,
          success: res => {
            this.setData({
              openid: res.data.openid
            })
          }
        })
      }


})  

php代码:

php代码较为简单,使用file_get_contents()方式即可;

<?php

// 接收get传参 code;
$code = $_GET['code'];
//你的appid,在小程序公众平台查看
$appid = 'xxxxxxxxxxxxxx';
//你的秘钥,在小程序公众平台获取
$secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx';

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

$wxuserinfo = file_get_contents($url,true);

//获取openid
$openid = json_decode($wxuserinfo,true)['openid'];

//当前返回的只有openid
echo $openid;

/*
如果要获取openid和session_key,可以跳过以下这两步

$wxuserinfo = file_get_contents($url,true);
$openid = json_decode($wxuserinfo,true)['openid'];

执行以下代码即可获取session_key和openid:
$wxuserinfo = file_get_contents($url);
echo $wxuserinfo

*/

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值