小程序后端获取openid (php实例)

小程序获取openid

首先,小程序授权登录的时候,前端就会获取到code

而后端接收到了code之后,就可以向微信发起请求,获取用户的openid代码如下:

<?php

    $code = $_REQUEST['code'];
    $secret = "你的appsecret";
    $appid = "你的appid";
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";

    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_TIMEOUT,30);

    $content = curl_exec($ch);
    $status = (int)curl_getinfo($ch,CURLINFO_HTTP_CODE);
    if ($status == 404) {
        return $status;
    }
    curl_close($ch);
    print_r($content);

 

posted @ 2020-03-03 15:36  钧一  阅读(2422)  评论(0编辑  收藏  举报