欢迎转载,请支持原创,保留原文链接:blog.ilibrary.me

我用react native, React native可以用react-native-wechat来获取微信用户code,

WeChat.sendAuthRequest("snsapi_userinfo").then(
    (response)=>{
        console.log(response)
        Network.loginViaWechat(response.code)
            .then(user=>{
                console.log(user)
            }).catch(error =>{
                console.log(error);
        })

        // this.getOpenId(response.code);
    }
).catch((error) => {
    let errorCode = Number(error.code);
    if (errorCode === -2) {
        this.showAlert('已取消授权登录'); // errorCode = -2 表示用户主动取消的情况,下同
    } else {
        this.showAlert('微信授权登录失败');
    }
})

react-native-wechat的配置详见Build setup for iOS. 注意添加下面的行到AppDelegate.m:

// ios 9.0+
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
            options:(NSDictionary<NSString*, id> *)options
{
  return [RCTLinkingManager application:application openURL:url options:options];
}

rails 端可以用wechat来实现code换用户信息的逻辑.

def create
    code = params[:code]
    res = Wechat.api.web_access_token(code) # 第一步,code换取access_token和openid
    openid = res['openid']
    unionid = res['unionid']
    access_token = res['access_token']
    # openid = "oiWo445A9vVeZ49dmdz5VhrccAjg"
    # session_key = "bHX0jIrSer0T5g0cYXpFoQ=="

    login_user = User.find_or_initialize_by(openid: openid)
    if(not login_user.persisted?)
      user_info = Wechat.api.web_userinfo(access_token, openid) # 第二步,获取用户信息,这一步可以只做一次。
      # {"openid"=>"ogdA70kNhVQem0nOlwzGqvdWaUtM",
      #  "nickname"=>"北冥",
      #  "sex"=>2,
      #  "language"=>"zh_CN",
      #  "city"=>"",
      #  "province"=>"",
      #  "country"=>"卢森堡",
      #  "headimgurl"=>"http://thirdwx.qlogo.cn/mmopen/vi_32/X9TSedH6J3xwibibIsQeTcPAiaRy5ib9fhs4fze6mG4KCGZabnzu05wwlRPAf3RDXFm9keGp998aGrwyQfbh382ziaQ/132",
      #  "privilege"=>[],
      #  "unionid"=>"oVcvaw1RrgplBo0i-hJY7CUEsZcY"}
        Rails.logger.info user_info
        login_user.email = "#{openid}@wechat.com" unless login_user.email.present?
        login_user.openid = openid
        login_user.unionid = unionid
        login_user.avatar = user_info["headimgurl"]
        login_user.skip_password_validation = true
      login_user.name = user_info["nickname"]
      login_user.wechat_user_info = user_info
        # login_user.confirmed_at = Time.zone.now if login_user.new_record?
        login_user.save!
    end

    render json:user
end