欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

微信小程序实现微信登录 小程序API接口攻击防护 微信小程序 网站后台 防止批量攻击 有大用 有大大用 有大大大用

微信小程序实现微信登录

96 
黄秀杰 关注            
2017.05.17 20:34* 字数 538 阅读 10499评论 1喜欢 6            

文档出处:https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html            

步骤:

1.调用wx.login得到code            

返回的结果示例:

{
  code:"051nI5Pa1XJkDs0773Pa1OWYOa1nI5PF"
  errMsg:"login:ok"
}
           

2.拿code换取session_key与openid            

这里使用服务端来请求,以php为例

$code = $this->input->post('code');
$json = 'https://api.weixin.qq.com/sns/jscode2session?appid='.WxPayConfig::APPID.'&secret='.WxPayConfig::APPSECRET.'&js_code='.$code.'&grant_type=authorization_code';
header("Content-Type: application/json");
echo file_get_contents($json);
           

其中appid与appsecret换成自己小程序的

得到的返回结果如下:

{
  "session_key": "odMd5E1qJI5KJH7OTBVZYg==",
  "expires_in": 7200,
  "openid": "oqMjq0BqLl6mRarbByCf9rOAc3k0"
}
           

4.生成用户或登录用户            

如果该openid不存在于数据库中,认为是新用户,注册它,如果openid已存在于数据库,认为是老用户。

php代码如下:

<?php
class User_model extends CI_Model {
    // 当前用户
    private $user;

    // 注册或更新用户
    public function registOrUpdate($data) {
        if ($this->verify($data)) {
            $this->update(['session_key' => $data->session_key], ['uid' => $this->user->uid]);
        } else {
            $this->regist($data);
        }
        $response = [
            'thirdSession' => $this->generate3rdSession()
        ];
        echo json_encode($response);
    }

    // 注册用户
    private function regist($data) {
        $this->db->insert('user', $data);
    }

    // 更新用户
    private function update($user, $condition) {
        $this->db->update('user', $user, $condition);
    }

    // 检测用户是否存在
    private function verify($data) {
        $query = $this->db->get_where('user', ['openid'=>$data->openid]);
        $user = $query->first_row();
        $this->user = $user;
        if ($query->num_rows()) {
            return true;
        }
        return false;
    }
}
           

5.服务端生成自己的3rd_session            

    // 创建随机数
    private function generate3rdSession() {
        return md5(mt_rand() . $this->user->openid);
    }
           

在registOrUpdate方法的最末尾加上如下代码调用:

        $response = [
            'thirdSession' => $this->generate3rdSession()
        ];
        echo json_encode($response);
           

经上,3rd_session发送到了小程序客户端,接下来要做的是将它保存到storage中,以便于后续的每次wx.request()调用。

提示:按照官方文档的时序图来看,以上的随机还是真随机,它不是良好示范,对安全严谨的用途,谨慎使用。

登录时序图                
登录时序图

6.小程序端本地存储服务端传来的3rd_session            

//发起网络请求
wx.request({
  url: 'http://localhost:3000/index.php/WXLogin/getSession',
  data: {
    code: res.code
  },
  header: {
    "content-type": "application/x-www-form-urlencoded"
  },
  method: 'POST',
  success: function (res) {
    // 保存3rdSession到storage中
    wx.setStorage({
      key:"thirdSession",
      data: res.data.thirdSession
    })
  },
  fail: function (res) {
    console.log(res);
  }
})
           

附加福利——换取union_id打通公众号与小程序用户体系

需要用到wx.getUserInfo,https://mp.weixin.qq.com/debug/wxadoc/dev/api/open.html#wxgetuserinfoobject,从小程序端传入$encryptedData, $iv到服务端,需要用到官方提供好的解密sdk,https://mp.weixin.qq.com/debug/wxadoc/dev/demo/aes-sample.zip,其中包含了php示例代码,对它简单的复制粘贴如下


    // 获取unionid
    private function getUnionId($encryptedData, $iv) {
               require_once __DIR__ . '/../third_party/aes/wxBizDataCrypt.php';

        $appid = 'wxcb935c2ec6734f08';
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );

        if ($errCode == 0) {
            $obj = json_decode($data);
            var_dump($obj->unionId);
            // unset($array["watermark"]);
            return [
                'unionid' => $obj->unionId,
                'nickname' => $obj->nickName,
                'avatarUrl' => $obj->avatarUrl,
                'gender' => $obj->gender,
                'country' => $obj->country,
                'province' => $obj->province,
                'city' => $obj->city,
                'language' => $obj->language
            ];
        } else {
            print($errCode . "\n");
        }
    }
           

这样就得到了unionid,就可以与自己的同一开发平台的帐号体系下的应用打通了,否则不会返回unionid。

这里有个坑,就是要把require_once放在getUnionId方法体内,而不是类顶部,因为为干扰header("Content-type: application/json")的输出,导致小程序端拿到的res.data是string而不是json对象。

最后成功存到了数据库,得到自己关心的信息。

                   
unionid.png

注意要先将小程序挂载在开放平台下

                   
bind.png

小程序端源码:http://git.oschina.net/dotton/demo-wx            

小礼物走一走,来简书关注我

赞赏支持
     小程序    
    © 著作权归作者所有
    96关注黄秀杰         

    写了 23119 字,被 86 人关注,获得了 95 个喜欢

    前端开发者,写过iOS、Android、Web。目前从事小程序开发。
    喜欢            
     
    6            
       更多分享    


                   
    登录 后发表评论                
    1条评论 只看作者                        
    按时间倒序按时间正序                        
                                   
     
    吃虾不吃头                                
    2楼 · 2018.07.15 16:40                                

    wx.getuserinfo更新了
    不弹窗了 怎么办?

      回复                            

    来自  https://www.jianshu.com/p/6be259f355ee

    普通分类: