微信服務號開發-商城微信登錄


最近幫朋友寫了個微信服務號,服務號名字叫做十四行詩。沒錯是賣月餅的商城。

簡單介紹下微信登錄,與官方文檔不同,簡單畫了一下UML圖

 

 

簡單的說就是先建立了一個index.php(直接拍域名就過去了。),然后傳一個appid,微信公眾號后台能拿到

<?php
$appid = '';

header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri=http://www.xxx.com/oauth.php&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect');
?>

一個回調

header("Content-Type: text/html;charset=utf-8"); 
$code = $_GET['code'];
$state = $_GET['state'];
//換成自己的接口信息
$appid = '';
$appsecret = '';
if (empty($code)) $this->error('授權失敗');
$    = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
$token = json_decode(file_get_contents($token_url));
if (isset($token->errcode)) {
    echo '<h1>錯誤:</h1>'.$token->errcode;
    echo '<br/><h2>錯誤信息:</h2>'.$token->errmsg;
    exit;
}

獲取到一個token

$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;
//轉成對象
$access_token = json_decode(file_get_contents($access_token_url));
if (isset($access_token->errcode)) {
    echo '<h1>錯誤:</h1>'.$access_token->errcode;
    echo '<br/><h2>錯誤信息:</h2>'.$access_token->errmsg;
    exit;
}
$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN';
//轉成對象
$user_info = json_decode(file_get_contents($user_info_url));
if (isset($user_info->errcode)) {
    echo '<h1>錯誤:</h1>'.$user_info->errcode;
    echo '<br/><h2>錯誤信息:</h2>'.$user_info->errmsg;
    exit;
}

然后得到了user_info。這里面有用戶的openid(唯一加密后的微信號),用戶的頭像headimgurl,用戶的昵稱nickname

 

再然后把他存下來

function send_post($url, $post_data) {
    $postdata = http_build_query($post_data);
    $options = array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-type:application/x-www-form-urlencoded',
        'content' => $postdata,
        'timeout' => 15 * 60 // 超時時間(單位:s)
    )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return $result;
}

$post_data = array(
    'partner_code' => $user_info->openid,
    'name' => $user_info->nickname,
    'headurl' => $user_info->headimgurl
);
send_post('/member_register', $post_data);
//打印用戶信息
print_r($user_info);

header('location:/index.html');


setcookie('partner_code',$user_info->openid);
setcookie('name',$user_info->nickname);
setcookie('headurl',$user_info->headimgurl);

 

這邊一共用了2種存放,一種是post到數據庫,還有一種是直接存cookie

當然這邊存cookie的作用很大。后面會介紹一下。

 

這邊是綁定下入口鏈接以及

 

 

 

這邊就是最后的效果


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM