Blogger Information
Blog 9
fans 0
comment 0
visits 8379
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
微信小程序通过code获取openid
洒脱艸的博客
Original
930 people have browsed it
<?php

/**
 * desc: 获取小程序用户openid
 */


getOpenid();
function getOpenid() {
    $code = $_GET['code'];//小程序传来的code值
    $appid = 'wx4b55bb240aec2ee3';//小程序的appid
    $appSecret = '1f6f68884c1add6293cfa9b86e1f6bfd';// 小程序的$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, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    $file_contents = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $file_contents;
}
————————————————
版权声明:本文为CSDN博主「储物箱」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44849587/article/details/122331414


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post