unity使用Shar SDK登录微信和分享到微信好友朋友圈(Android)

       由于最近工作需要,需要微信的第三方登录和分享功能。自己在网上看了一些分享资料,然后选择了Share sdk来制作,中途也踩了不少的坑。在这里总结下来,让自己加强记忆,也避免遗忘。

一、配置环境修改SDK脚本

1、去官网下载Share SDk,注册一个账号,然后申请一个应用,记录下你的Appkey和AppSecret备用。

2、在微信开放平台申请一个移动应用(需要注册年审)。在申请的时候要注意包名和应用签名,包名就是player setting里面的Bundle Identifier:com.XXX.XXX;应用签名就是你的keystore的MD5,你可以选择用签名工具去获取或者自己重新导出一个keystore,要注意是MD5那一排序列号去掉中间的:,然后还要全部小写.然后等待腾讯审核通过你就能得到你的App ID和Secret。然后在Mob开发后台你中你刚刚申请的应用中的社会化平台设置中,选中微信填上你的微信应用的ID和Secret。

3、打开Unity工程,将下载下来的ShareSDK.unitypackage导入工程,寻找MOb的客服,提供你的包名,请他帮你打包一个Democallback.jar的包用于替换掉你工程里面的那个包。把Share SDK脚本放到你的任意物体上,然后需要把前2排的AppKey和AppSecret改成你在Mob平台申请的应用的AppKey和AppSecret,把WeChat和WeChatMoments中的App Id和App Secret更改为你的微信应用的ID和Secret。打开Plugins/Android/ShareSDK/AndroidManifest.xml文件将

package改成你的包名,然后将

name中的wxapi前加上你的包名。

然后打开ShareSDkDevInfo脚本,可以将你不需要的平台全部注释掉,然后把WeChat和WeChatMoments中的AppId和AppSecret改成你的微信的ID和Secret。在这里如果你分享的时候要绕过审核就不用管BypassApproval,如果不绕过就把这个bool值改成false,同样在unity的Inspect面板中要把Share SDK的BypassApproval的√去掉。

打开Share SDk脚本,将Appkey和AppSecret更改成你的Mob平台申请的应用的key和Secret。

到此,配置已经全部配完,需要修改的东西也已经改完,接下来就是开始写我们的微信登录和分享脚本。

二、微信登录与分享

1、使用ShareSDK登录微信

直接上代码,在代码注释中标注了一些注意事项,登录代码如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using cn.sharesdk.unity3d;

public class WeChatLogin : MonoBehaviour
{
    ShareSDK sharesdk;
//这里我登录之后需要获取到头像、昵称和OpenID
    private  Text UserNameText;
    private  Image UserIconImage;
    private static string UserName;
    private static string UserIcon;
    private static string UserOpenID;

    void Start()
    {
        sharesdk = GameObject.Find("Main Camera").GetComponent<ShareSDK>();
        UserNameText = GameObject.Find("Name").GetComponent<Text>();
        UserIconImage = GameObject.Find("Icon").GetComponent<Image>();
        sharesdk.authHandler += OnAuthResultHandler;//授权回调
        sharesdk.showUserHandler += OnGetUserInfoResultHandler;//获取用户信息

        GameObject.Find("WeChatLogin").GetComponent<Button>().onClick.AddListener(delegate
        {
            //print("登录");
            sharesdk.GetUserInfo(PlatformType.WeChat);//授权只有第一次是手动授权,之后都是自动授权,更改微信账号后会重新授权
        });
        GameObject.Find("WeChatCancelLogin").GetComponent<Button>().onClick.AddListener(delegate
        {
           // print("取消登录");
            sharesdk.CancelAuthorize(PlatformType.WeChat);
            CancelLogin();
        });
        GameObject.Find("text").GetComponent<Text>().text = sharesdk.IsAuthorized(PlatformType.WeChat)+"";

        if (sharesdk.IsAuthorized(PlatformType.WeChat))
            sharesdk.GetUserInfo(PlatformType.WeChat);
    }


    public void CancelLogin()//取消授权
    {
        if(!sharesdk.IsAuthorized(PlatformType.WeChat))//IsAuthorized可以判断授权是否有效
        {
            UserIcon = null;
            UserName = null;
            UserIconImage.sprite = null;
            UserNameText.text = null;
        }
    }
    void OnAuthResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
    {
        if (state == ResponseState.Success)
        {
            sharesdk.GetUserInfo(type);
        }
        else if (state == ResponseState.Fail)
        {
#if UNITY_ANDROID
            print("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
#elif UNITY_IPHONE
        print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
#endif
        }
        else if (state == ResponseState.Cancel)
        {
            print("cancel !");
        }
    }
    void OnGetUserInfoResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
    {
        if (state == ResponseState.Success)
        {
            switch (type)
            {
                case PlatformType.WeChat:
                    result = sharesdk.GetAuthInfo(PlatformType.WeChat);//获取到用户信息,可以在里面去到头像地址、用户名、OpenID等
                    UserIcon = (string)result["userIcon"];
                    UserName = (string)result["userName"];
                    UserOpenID = (string)result["openID"];
                    //GameObject.Find("text").GetComponent<Text>().text = MiniJSON.jsonEncode(result);
                    StartCoroutine(GetUserIcon(UserIcon));//获取到的头像是一个地址,所以使用www加载
     
                    break;
            }
        }
        else if (state == ResponseState.Fail)
        {
            print("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
        }
        else if (state == ResponseState.Cancel)
        {
            print("cancel !");
        }
    }
    IEnumerator GetUserIcon(string url)
    {
        WWW www = new WWW(url);
        yield return www;
        if (www != null && string.IsNullOrEmpty(www.error))
        {
            Texture2D texture = www.texture;
            Sprite iconSprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            UserIconImage.sprite = iconSprite;
            UserNameText.text = UserName;
        }
    }
}

2、微信好友与朋友圈的分享

也是直接上代码,注意点见注释。代码如下

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using cn.sharesdk.unity3d;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class WeChatShare : MonoBehaviour
{
    ShareSDK sharesdk;

    private GameObject SharePanel;

	void Start ()
    {
        sharesdk = GameObject.Find("Main Camera").GetComponent<ShareSDK>();
        sharesdk.shareHandler = OnShareResultHandler;//分享回调

        SharePanel = GameObject.Find("SharePanel").gameObject;

        GameObject.Find("WeChatShare").GetComponent<Button>().onClick.AddListener(delegate
        {
            if (sharesdk.IsAuthorized(PlatformType.WeChat))//判断是否授权,没授权则不能分享
            {
                //print("分享");
                ScreenShot();
            }
        });
        GameObject.Find("Friends").GetComponent<Button>().onClick.AddListener(delegate
        {
            //print("好友");
            ShareImage();
        });
        GameObject.Find("Moments").GetComponent<Button>().onClick.AddListener(delegate
        {
           // print("朋友圈");
            ShareImage();
        });

        SharePanel.SetActive(false);
    }
    public void ScreenShot()
    {
        Application.CaptureScreenshot("ShareImage.png");//屏幕截图
        SharePanel.SetActive(true);
    }
    public void ShareImage()
    {
        ShareContent content = new ShareContent();
        content.SetText("测试一下share sdk 分享功能");
        content.SetImagePath(Application.persistentDataPath+ "/ShareImage.png");//手机路径使用的是SetImagePath
        content.SetShareType(ContentType.Image);//分享的类型,image就是只分享图片
        content.SetTitle("测试");
        string BtnName = EventSystem.current.currentSelectedGameObject.name;
        switch (BtnName)
        {
            case "Friends":
                sharesdk.ShareContent(PlatformType.WeChat, content);//分享到微信好友
                break;
            case "Moments":
                sharesdk.ShareContent(PlatformType.WeChatMoments, content);//分享到微信朋友圈
                break;
            default:
                break;
        }
        
    }

    void OnShareResultHandler(int reqID, ResponseState state, PlatformType type, Hashtable result)
    {
        if (state == ResponseState.Success)
        {
            print("share successfully - share result :");
            print(MiniJSON.jsonEncode(result));
        }
        else if (state == ResponseState.Fail)
        {
            #if UNITY_ANDROID
            print("fail! throwable stack = " + result["stack"] + "; error msg = " + result["msg"]);
            #elif UNITY_IPHONE
			print ("fail! error code = " + result["error_code"] + "; error msg = " + result["error_msg"]);
            #endif
        }
        else if (state == ResponseState.Cancel)
        {
            print("cancel !");
        }
    }
}

至此,unity使用Shar SDK登录微信和分享到微信好友朋友圈的Android版本全部结束,iOS的等需要再试。

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值