微信小程序数据通信get/post curl抓取数据

demo:登录wx.login 发送 res.code 到后台换取 openId
//测试阶段:点击详情 勾选上不校验合法域名
// 登录 get 异步获取数据

  wx.login({
    success: res => {
      console.log(res);
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      //发给服务器端  http://localhost/web/demopro/wechat/getCode.php
      wx.request({
        url: 'http://localhost/web/demopro/wechat/getCode.php', //仅为示例,并非真实的接口地址
        method: "get",
        data: {
          code: res.code
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          //console.log(res.data)
          var data = res.data;
          var openid = JSON.parse(data).openid;
          //得到用户openid,存入数据库
          console.log(openid);
        }
      })

    }
  })

// 登录 post异步获取数据

wx.login({
  success: res => {
    console.log(res);
    // 发送 res.code 到后台换取 openId, sessionKey, unionId
    //发给服务器端  http://localhost/web/demopro/wechat/getCode.php
    wx.request({
      url: 'http://localhost/web/demopro/wechat/getCode.php', //仅为示例,并非真实的接口地址
      method: "post",
      data: {
        code: res.code
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // **********************post请求**************
      },
      success(res) {
        //console.log(res.data)
        var data = res.data;
        var openid = JSON.parse(data).openid;
        //得到用户openid,存入数据库
         console.log(openid);
      }
    })

  }
})

getCode.php代码如下:

//根据自己请求数据方式修改
$code=$_GET["code"];
//$code=$_POST["code"];
//得到code换取openid
//https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
$url="https://api.weixin.qq.com/sns/jscode2session?appid=wx1a742e9678438791&secret=7dd080428fdd458e1e184a3ab890fd20&js_code=$code&grant_type=authorization_code";
$data=curl($url,"get","https");
echo $data;
//封装curl 抓取数据
 function curl($url, $method = "get", $type = "http", $data = "")
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    if ($type == "https") {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//不做服务器认证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//不做客户端认证
    }
    if ($method == "post") {
        curl_setopt($ch, CURLOPT_POST, true);//设置请求是POST方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置POST请求的数据
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    curl_close($ch);
    return json_encode($data);
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值