Unity

微信登陆

AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
		AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
		jo.Call("wxLogin");

微信分享

AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.Call("wxShare", "你分享的链接", "分享标题", "分享内容");

接收微信登录授权后得到的code,以获取头像昵称等

public void funName(string code) {
       //根据code值获取openid  token等 以获取玩家头像 昵称
       //UnityWebRequest
    }

跳转到微信文档(登录,code获取头像昵称)

AndroidStudio

一.引入wxsdk

unity没法用微信登录 unity 微信登录_unity3d


build.gradle dependencies加入以下代码,编译引入微信sdk

implementation 'com.tencent.mm.opensdk:wechat-sdk-android-with-mta:+'
二.初始化微信sdk

UnityPlayerActivity.java

public IWXAPI wxApi;
    public static String appId;
    // Setup activity layout
    @Override protected void onCreate(Bundle savedInstanceState)
    {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        wxInit("你的微信appid");
    }
    
    public void wxInit(String id){
        appId = id;
        wxApi = WXAPIFactory.createWXAPI(this, appId, false);
    }
三.创建必要的回调文件

android项目,如下图路径创建wxapi文件夹,文件夹名字wxapi不可变更!

unity没法用微信登录 unity 微信登录_微信_02


wxapi文件夹下创建java脚本WXEntryActivity,如下图:

脚本名字WXEntryActivity不可变更

unity没法用微信登录 unity 微信登录_微信_03


脚本内容如下

package com.xxx.xxx.wxapi;//wxapi前面是你的bundleID

import android.os.Bundle;


import com.ddwj.ddwz.az.UnityPlayerActivity;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unity3d.player.UnityPlayer;

import android.app.Activity;
import android.util.Log;


public class WXEntryActivity extends Activity  implements IWXAPIEventHandler{
    public IWXAPI wxApi;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        final String appId = UnityPlayerActivity.appId;

        wxApi = WXAPIFactory.createWXAPI(this, appId, false);
        super.onCreate(savedInstanceState);
        try
        {
            boolean handleIntent = wxApi.handleIntent(getIntent(), this);
            if(!handleIntent){
                System.out.println("参数不合法");
                finish();
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    // 微信发送请求到第三方应用时,会回调到该方法
    @Override
    public void onReq(BaseReq baseReq) {

    }

    // 第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
    @Override
    public void onResp(BaseResp baseResp) {
        Log.e("unity_2_android", "onResp: " );
        System.out.println("unity_2_android微信响应" + baseResp.errCode);
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                System.out.println("unity_2_android用户同意");
                if(baseResp instanceof SendAuth.Resp)
                {
                    SendAuth.Resp newResp = (SendAuth.Resp) baseResp;
                    String code = newResp.code;
                    //传出微信返回的code信息 到Unity处理
  					UnityPlayer.UnitySendMessage("unity挂载接收code值的节点名","unity用来接收code的方法名",code);
                }
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                System.out.println("unity_2_android用户拒绝授权" + baseResp.openId);
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                System.out.println("unity_2_android用户取消");
                break;
        }
        finish();
    }
}
四.AndroidStudio提供给Unity调用的方法

UnityPlayerActivity.java脚本加入如下代码

public void wxLogin(){
       
        if(null == wxApi) {
            wxApi = WXAPIFactory.createWXAPI(this, appId, false);
            if(null == wxApi)
            {
                System.out.println("微信登录失败...");
                return;
            }
            wxApi.registerApp(appId);
        }
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        wxApi.sendReq(req);
    }
    /**
     * 分享网页类型至微信
     *
     * @param url 分享链接
     * @param title 分享标题
     * @param desc 分享内容
     */
    public void wxShare(String url, String title,String desc){
        Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.app_icon);
        shareWeb(this,appId,url,title,desc,thumbBmp);
    }
    /**
     * 分享网页类型至微信
     *
     * @param context 上下文
     * @param appId   微信的appId
     * @param webUrl  网页的url
     * @param title   网页标题
     * @param desc 网页描述
     * @param bitmap  位图
     */
    public  void shareWeb(Context context, String appId, String webUrl, String title, String desc, Bitmap bitmap) {

        wxApi = WXAPIFactory.createWXAPI(this, appId, false);
        // 检查手机或者模拟器是否安装了微信
        if (!wxApi.isWXAppInstalled()) {
//            ToastUtil.makeText("您还没有安装微信");
            UnityPlayer.UnitySendMessage("PanelWallet","showTip","您还没有安装微信");
            return;
        }

        // 初始化一个WXWebpageObject对象
        WXWebpageObject webpageObject = new WXWebpageObject();
        // 填写网页的url
        webpageObject.webpageUrl = webUrl;

        // 用WXWebpageObject对象初始化一个WXMediaMessage对象
        WXMediaMessage msg = new WXMediaMessage(webpageObject);
        // 填写网页标题、描述、位图
        msg.title = "";
        msg.description = desc;
        // 如果没有位图,可以传null,会显示默认的图片
        msg.setThumbImage(bitmap);

        // 构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        // transaction用于唯一标识一个请求(可自定义)
        req.transaction = "webpage";
        // 上文的WXMediaMessage对象
        req.message = msg;
        // SendMessageToWX.Req.WXSceneSession是分享到好友会话
        // SendMessageToWX.Req.WXSceneTimeline是分享到朋友圈
        req.scene = SendMessageToWX.Req.WXSceneSession;

        // 向微信发送请求
        wxApi.sendReq(req);
    }

wxLogin为微信授权登录
wxShare为微信分享

下面是我的code获取头像昵称的方法,没有整理,仅供参考
public void funName(string code) {
//授权登录后android返回的code
       //根据code值获取openid  token等 以获取玩家头像 昵称
       //UnityWebRequest
       this.code = code;
       StartCoroutine("SendRequest_data");
    }
void refreshToken(){
        refresh_token = PlayerPrefs.GetString("refresh_token");
        
        if(refresh_token==""){
            //绑定登录
            Debug.Log("去绑定登录");
            

        }else{
        	//显示本地存储的头像和昵称
            string headUrl= PlayerPrefs.GetString("headUrl_local");
            string nick = PlayerPrefs.GetString("nick_local");
            text_wxNick.text = nick;
            SetPlayerIcon(img_icon, headUrl);

			//可选择是否刷新token并获取最新的头像昵称
           // StartCoroutine("SendRequest_refreshData");
            

        }
    }



IEnumerator SendRequest_data() {
        
        Uri uri = new Uri("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code");
        UnityWebRequest webRequest = UnityWebRequest.Get(uri);

        webRequest.timeout = 5;
        yield return webRequest.SendWebRequest();                     //等待返回请求的信息
        if (webRequest.isHttpError || webRequest.isNetworkError)             //如果其 请求失败,或是 网络错误
        {
            Debug.LogError("unity_2_" + webRequest.error); //打印错误原因
        }
        else //请求成功
        {
            Debug.Log("unity_2_请求成功--获取openid");
            WX_Data wx_data = JsonConvert.DeserializeObject<WX_Data>(webRequest.downloadHandler.text);
            refresh_token = wx_data.refresh_token;
            StartCoroutine("SendRequest_refreshData");
            
        }
    }

    IEnumerator SendRequest_refreshData() {
       // https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
        Uri uri = new Uri("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + appId + "&grant_type=refresh_token&refresh_token=" + refresh_token );
        UnityWebRequest webRequest = UnityWebRequest.Get(uri);

        webRequest.timeout = 5;
        yield return webRequest.SendWebRequest();                     //等待返回请求的信息
        if (webRequest.isHttpError || webRequest.isNetworkError)             //如果其 请求失败,或是 网络错误
        {
            Debug.LogError("unity_2_" + webRequest.error); //打印错误原因
        }
        else //请求成功
        {
			
            Debug.Log("unity_2_请求成功--获取openid");
            wX_RefreshData = JsonConvert.DeserializeObject<WX_RefreshData>(webRequest.downloadHandler.text);
            refresh_token = wX_RefreshData.refresh_token;
            PlayerPrefs.SetString("refresh_token",refresh_token);
            StartCoroutine("SendRequest_checkToken");
        }
    }

    IEnumerator SendRequest_checkToken() {
        //https://api.weixin.qq.com/sns/auth?access_token=ACCESS_TOKEN&openid=OPENID
        Uri uri = new Uri("https://api.weixin.qq.com/sns/auth?access_token=" + wX_RefreshData.access_token + "&openid=" + wX_RefreshData.openid);
        UnityWebRequest webRequest = UnityWebRequest.Get(uri);

        webRequest.timeout = 5;
        yield return webRequest.SendWebRequest();                     //等待返回请求的信息
        if (webRequest.isHttpError || webRequest.isNetworkError)             //如果其 请求失败,或是 网络错误
        {
            Debug.LogError("unity_2_" + webRequest.error); //打印错误原因
        }
        else //请求成功
        {

            Debug.Log("unity_2_请求成功--校验token");
            WX_Code code = JsonConvert.DeserializeObject<WX_Code>(webRequest.downloadHandler.text);
            if (code.errcode == 0) {
                Debug.Log("unity_2检验授权凭证(access_token)有效");
                StartCoroutine("SendRequest_userInfo");
            }
            else {
                Debug.Log("unity_2检验授权凭证(access_token)无效,code=" + code.errcode + ",msg=" + code.errmsg);
            }
        }
    }

    IEnumerator SendRequest_userInfo() {
        //https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
        Uri uri = new Uri("https://api.weixin.qq.com/sns/userinfo?access_token=" + wX_RefreshData.access_token + "&openid=" + wX_RefreshData.openid);
        UnityWebRequest webRequest = UnityWebRequest.Get(uri);

        webRequest.timeout = 5;
        yield return webRequest.SendWebRequest();                     //等待返回请求的信息
        if (webRequest.isHttpError || webRequest.isNetworkError)             //如果其 请求失败,或是 网络错误
        {
            Debug.LogError("unity_2_" + webRequest.error); //打印错误原因
        }
        else //请求成功
        {

            Debug.Log("unity_2_请求成功--玩家信息");
            wx_UserInfo = JsonConvert.DeserializeObject<WX_UserInfo>(webRequest.downloadHandler.text);
            Debug.Log("unity_2_请求成功--玩家信息:" + webRequest.downloadHandler.text);
            node_wxBind.gameObject.SetActive(false);
            node_wxInfo.gameObject.SetActive(true);
            text_wxNick.text = wx_UserInfo.nickname;
            SetPlayerIcon(img_icon, wx_UserInfo.headimgurl);
            headUrl_local = wx_UserInfo.headimgurl;
            nick_local = wx_UserInfo.nickname;
            PlayerPrefs.SetString("headUrl_local", wx_UserInfo.headimgurl);
            PlayerPrefs.SetString("nick_local", nick_local);
            PlayerPrefs.SetString("openid", wX_RefreshData.openid);

            UserDataMgr.Instance.openid =  wX_RefreshData.openid;
            
            PlayerPrefs.SetInt("lastGetUserInfoTime",Tools.GetCurTime());
        }
    }


    // 对自己的头像做缓存
    private Sprite selfIcon;
    /// <summary>
    /// 设置玩家的头像 微信或本地
    /// </summary>
    /// <param name="imgIcon">sprite</param>
    /// <param name="url">头像url</param>
    public void SetPlayerIcon(Image imgIcon, string url) {
        if (imgIcon == null) return;
        if (string.IsNullOrEmpty(url)) {
            return;
        }
        bool isSelf = url == headUrl_local;
        if (isSelf && selfIcon != null) {
            imgIcon.sprite = selfIcon;
            return;
        }
        StartCoroutine("GetImage", url);
    }




    IEnumerator GetImage(string url) {
        Debug.Log("unity_2   " + url);
        string str = url.Replace("\\", string.Empty);
        Debug.Log("unity_2   " + str);
        WWW www = new WWW(str);
        yield return www;
        if (string.IsNullOrEmpty(www.error)) {
            Texture2D tex = www.texture;
            Sprite temp = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(0, 0));
            this.img_icon.sprite = temp; //设置的图片,显示从URL图片
        }
    }
public class WX_Data {
    public string access_token { get; set; }
    public int expires_in { get; set; }
    public string refresh_token { get; set; }
    public string openid { get; set; }
    public string scope { get; set; }
    public string unionid { get; set; }
}
public class WX_RefreshData{

    public string access_token{get;set;}
    public int expires_in{get;set;}
    public string refresh_token{get;set;}
    public string openid{get;set;}
    public string scope{get;set;}
}
public class WX_Code {
    public int errcode { get; set; }
    public string errmsg { get; set; }
}


public class WX_UserInfo {
    public string openid { get; set; }
    public string nickname { get; set; }
    public int sex { get; set; }
    public string province { get; set; }
    public string city { get; set; }
    public string country { get; set; }
    public string headimgurl { get; set; }
    public string[] privilege { get; set; }
    public string unionid { get; set; }
}