天天看點

PHP擷取小程式open_id

<?php
getOpenid();
function getOpenid() {
    $code = $_GET['code'];//小程式傳來的code值
    $appid = 'wx4b55bb*****ec2ee3';//小程式的appid
    $appSecret = '1f6f68884c1add6293******e1f6bfd';// 小程式的$appSecret
    $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
    $getUrl = sprintf($wxUrl, $appid, $appSecret, $code);//把appid,appsecret,code拼接到url裡
    $result = curl_get($getUrl);//請求拼接好的url
    $wxResult = json_decode($result, true);
    if (empty($wxResult)) {
        echo '擷取openid時異常,微信内部錯誤';
    } else {
        $loginFail = array_key_exists('errcode', $wxResult);
        if ($loginFail) {//請求失敗
            var_dump($wxResult);
        } else {//請求成功
            $openid = $wxResult['openid'];
            echo "擷取openid成功成功:" . $openid;
        }
    }
}

//php請求網絡的方法
function curl_get($url, &$httpCode = 0) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //不做證書校驗,部署在linux環境下請改為true
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
}