unity接微信androidSDK,一个供参考测试的Demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AXuan_K/article/details/60780370


首先 搭建环境的工作我不多说, 网上可以搜到一大堆;

然后 需要用到的请求还得读一读官方文档

文档: 微信授权后http请求接口

文档:分享给好友,朋友圈




这个是微信登录授权后拉取到的用户信息




unity代码部分经过简单的封装

unity 调androidSDK  首先需要 _GetCurrentAndroidJavaObject() 得到AndroidJavaObj jo;

jo.Call<T>(apiName, args) 中  T代表返回类型, apiName 是SDK中的函数名, args则是对应函数的



unity c#部分代码:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.Collections.Generic;
using System;

public class test : MonoBehaviour {

    private Text txt;
    string headimgurl;

    // Use this for initialization
    void Start () {
        GameObject btnObj = GameObject.Find("Canvas/Button");   //获取按钮脚本组件
         Button btn = (Button)btnObj.GetComponent<Button>();
        GameObject btnObj1 = GameObject.Find("Canvas/Button1");   //获取按钮脚本组件
        Button btn1 = (Button)btnObj1.GetComponent<Button>();
        GameObject btnObj2 = GameObject.Find("Canvas/Button2");   //获取按钮脚本组件
        Button btn2 = (Button)btnObj2.GetComponent<Button>();
        GameObject btnObj3 = GameObject.Find("Canvas/Button3");   //获取按钮脚本组件
        Button btn3 = (Button)btnObj3.GetComponent<Button>();
        GameObject btnObj4 = GameObject.Find("Canvas/Button4");   //获取按钮脚本组件
        Button btn4 = (Button)btnObj4.GetComponent<Button>();
        GameObject btnObj5 = GameObject.Find("Canvas/Button5");   //获取按钮脚本组件
        Button btn5 = (Button)btnObj5.GetComponent<Button>();
        GameObject btnObj6 = GameObject.Find("Canvas/Button6");   //获取按钮脚本组件
        Button btn6 = (Button)btnObj6.GetComponent<Button>();
        GameObject textObj = GameObject.Find("Canvas/Text");   //获取按钮脚本组件
        txt = (Text)textObj.GetComponent<Text>();
        //添加点击侦听
        btn.onClick.AddListener(onClick);
        btn1.onClick.AddListener(onClick1);
        btn2.onClick.AddListener(onClick2);
        btn3.onClick.AddListener(onClick3);
        btn4.onClick.AddListener(onClick4);
        btn5.onClick.AddListener(onClick5);
        btn6.onClick.AddListener(onClick6);
    }
	
	// Update is called once per frame
	void Update () {
	
	}
    
    AndroidJavaObject _GetCurrentAndroidJavaObject()                //要有这个AndroidJavaObject才能Call
    {
        AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        return jc.GetStatic<AndroidJavaObject>("currentActivity");
    }

    protected void _CallSdkApi(string apiName, params object[] args)             //没有返回值的Call
    {

        AndroidJavaObject jo = _GetCurrentAndroidJavaObject();
        jo.Call(apiName, args);
    }

    protected T _CallSdkApiReturn<T>(string apiName, params object[] args)          //模板只是返回参数类型不同
    {

        AndroidJavaObject jo = _GetCurrentAndroidJavaObject();
        return jo.Call<T>(apiName, args);
    }
    
    void onClick()
    {
        txt.text = "按钮1";
        string[] str = new string[] { "http://blog.csdn.net/axuan_k", "---title----", "---description---" };
        _CallSdkApi("SdkScenetimeline", str);
    }
    void onClick1()
    {
        txt.text = "按钮2";
        string[] str = new string[] { "消息的内容 msg" };
        _CallSdkApi("SdkSendMsg", str);

    }
    void onClick2()
    {
        txt.text = "按钮3";
        string[] str = new string[] { "http://blog.csdn.net/axuan_k", "---title----", "---description---" };
        _CallSdkApi("SdkInvitation", str);
       
    }
    void onClick3()
    {
        txt.text = "按钮4";
        _CallSdkApi("SdkLogin");  
    }
    void onClick4()
    {
        int netType = _CallSdkApiReturn<int>("SdkAskNetType");

        txt.text = "按钮5   " + "type (-1:没有网络)  (1:WIFI网络)(2:cmwap网络)(3:cmnet网络 ) \n" + "type: "+ netType.ToString();
    }
    void onClick5()
    {
        float value = _CallSdkApiReturn<float>("SdkAskNetSignal");

        txt.text = "按钮6" + "信号范围-100 到 0, 0信号最好    value: "+ value.ToString();
    }
    void onClick6()
    {
        float v = _CallSdkApiReturn<float>("SdkAskBattery");
        txt.text = "按钮7  value:" + v.ToString();
    }

    void json_AcToken(string str)                       
    {
        Dictionary<string, object> JsonGet = MiniJSON.Json.Deserialize(str) as Dictionary<string, object>;
        txt.text = "解json之前";
        string openid = JsonGet["openid"].ToString();
        string access_token = JsonGet["access_token"].ToString();
        txt.text = "授权信息: " + "\nopenID:" + openid + "\naccess_token" + access_token;

       string[] str2 = new string[] { access_token, openid };
        _CallSdkApi("GetUserInfoReq", str2);

    }

    void json_UserInfo(string str)
    {
        //  string[] str2 = new string[] { "微信传回来的呃呃呃额额: " + str };
       // txt.text = "解json之前";
        Dictionary<string, object> JsonGet = MiniJSON.Json.Deserialize(str) as Dictionary<string, object>;
      //  txt.text = "解json之后 str:" + str;
        string openid = JsonGet["openid"].ToString();
        string nickname = JsonGet["nickname"].ToString();
        string sex = JsonGet["sex"].ToString();
        string province = JsonGet["province"].ToString();
        string city = JsonGet["city"].ToString();
        string country = JsonGet["country"].ToString();
        string headimgurl = JsonGet["headimgurl"].ToString();          //头像是一个链接还得下载下来.....
        string unionid = JsonGet["unionid"].ToString();
        txt.text = "用户信息: " + "\nopenID:" + openid + "\nnickname:" + nickname
            + "\nsex" + sex + "\nprovince" + province + "\ncity" + city + "\ncountry" + country
            + "\nheadimgurl" + headimgurl + "\nunionID" + unionid;
    }
}





AndoridSDK调用unity c#

UnityPlayer.UnitySendMessage("Canvas","json_AcToken",a_t_r);      Canvas是场景中的游戏对象, json_AcToken表示游戏对象中某个脚本的函数名 , a_t_r及之后的则是参数


AndoridSDK 部分代码:

package com.joyyou.tank.wxapi;

import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.TargetApi;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.Toast;

import com.tencent.mm.sdk.openapi.BaseReq;
import com.tencent.mm.sdk.openapi.BaseResp;
import com.tencent.mm.sdk.openapi.ConstantsAPI;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.sdk.openapi.SendAuth;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mm.sdk.openapi.WXImageObject;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;
import com.tencent.mm.sdk.openapi.WXWebpageObject;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class WXEntryActivity extends UnityPlayerActivity implements IWXAPIEventHandler {
	public static final String APP_ID = "1";
	public static final String APP_Se ="2";
	public static final String url1 ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=";
	public String furl,a_t_r;
	private Vibrator mVibrator01;
	public String a_t,openId;
	Context mContext = null;
	private IWXAPI api;
	JSONObject Ajson ;
	@Override
  	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		api = WXAPIFactory.createWXAPI(this, APP_ID, true);        
      	api.registerApp(APP_ID);
      	api.handleIntent(getIntent(), this);       
	}
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		Uri uri = getIntent().getData();
      	if (uri != null) {	
     // 		UnityPlayer.UnitySendMessage("test","asd",uri.toString());
      	}
	}
 
    public void SdkSendMsg(String str)                     	//微信分享一条消息给好友
    {
    	WXTextObject textObj = new WXTextObject();
    	textObj.text = str;
    	WXMediaMessage msg = new WXMediaMessage();
    	msg.mediaObject = textObj;
    	msg.description = str;
    	SendMessageToWX.Req req = new SendMessageToWX.Req();
    	req.transaction = buildTransaction("tex"); 
    	req.message = msg;
    	req.scene = SendMessageToWX.Req.WXSceneSession;
    	api.sendReq(req);
    }
    
    public void SdkInvitation(String name,String titl,String des)          //微信发一个链接给好友
    {    
    	WXWebpageObject webpage = new WXWebpageObject();
    	webpage.webpageUrl = name;
    	WXMediaMessage msg = new WXMediaMessage(webpage);
    	msg.title = titl;
    	msg.description = des;
    	SendMessageToWX.Req req = new SendMessageToWX.Req();
    	req.transaction = buildTransaction("webpage");
    	req.message = msg;
    	req.scene = SendMessageToWX.Req.WXSceneSession;
    	api.sendReq(req);
    }
    
    public void SdkScenetimeline(String name,String titl,String des)  //  微信朋友圈分享
    {  
    	WXWebpageObject webpage = new WXWebpageObject();
    	webpage.webpageUrl = name;
    	WXMediaMessage msg = new WXMediaMessage(webpage);
    	msg.title = titl;
    	msg.description = des;
    	SendMessageToWX.Req req = new SendMessageToWX.Req();
    	req.transaction = buildTransaction("webpage");
    	req.message = msg;
    	req.scene = SendMessageToWX.Req.WXSceneTimeline;
    	api.sendReq(req);
    }
    
    public void SdkTest(String str)                  //屏幕中下显示一条消息
    {
    	Toast.makeText(WXEntryActivity.this, str, Toast.LENGTH_LONG).show();
    }
    
    public void SdkLogin()                           //微信登录请求 , 这步执行成功后会弹出微信
    {
    	SendAuth.Req req = new SendAuth.Req();
    	req.scope = "snsapi_userinfo";
    	req.state = "wechat_sdk_demo_test";
    	api.sendReq(req);                  
    }
    
    public int SdkAskNetType()             //网络类型
    {
    	return GetNetype((Context) WXEntryActivity.this);
    }
    
    public float SdkAskNetSignal()         //wifi信号强度
    {
    	return ((WifiManager)getSystemService(WIFI_SERVICE)).getConnectionInfo().getRssi();
    }
    
    @SuppressWarnings("deprecation")
	public float SdkAskBattery()           //电量剩余
    {
    	int sdkVersion;
    	float battery;  
        try 
        {  
            sdkVersion = Integer.valueOf(android.os.Build.VERSION.SDK); 
            SdkTest(""+sdkVersion);
        } 
        catch (NumberFormatException e) 
        {  
            sdkVersion = 0;  
            SdkTest("------"+sdkVersion);
        } 
        if (sdkVersion >= 21)                    
        {
        	battery=highBattery();
        }
        else 
        {
        	battery=lowBattery();               //低版本怎么获取呢。。。
        
        }
        return battery;
    }
    
    public void SdkScreenshot(byte[] str,int len)                   //给好友分享一张图片
    {
    	Bitmap bit = Bytes2Bimap(str);
    	WXImageObject img = new WXImageObject(bit);
    	WXMediaMessage msg = new WXMediaMessage();
    	msg.mediaObject = img;
    	SendMessageToWX.Req req = new SendMessageToWX.Req();
    	req.transaction = buildTransaction("img");
    	req.message = msg;
    	req.scene = SendMessageToWX.Req.WXSceneSession;
    	api.sendReq(req);
    }
  
    public void SdkOpenWeb(String url)                        //打开一个网页链接      
    {    	
    	Uri uri=Uri.parse(url);  
    	Intent intent=new Intent(Intent.ACTION_VIEW,uri);  
    	startActivity(intent); 
    }
    
    public void SdkPhoneshake(){                          //震动一下
         mVibrator01 = ( Vibrator ) getApplication().getSystemService(Service.VIBRATOR_SERVICE);  
         mVibrator01.vibrate( new long[]{200,10,200,1000},-1);  
    }
    
    protected void onNewIntent(Intent intent) {       
    	super.onNewIntent(intent);
    	setIntent(intent);
        api.handleIntent(intent, this);
    }

    private String buildTransaction(final String type) {                       
    	return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
    
    public void onReq(BaseReq req) {
    
    }
    
    
    public void onResp(BaseResp resp) {              //系统中的微信作出相应后会调用这个函数        
    //	Toast.makeText(WXEntryActivity.this, resp.errCode+"".toString(), Toast.LENGTH_LONG).show();
    	//注意了errCode = -6   就是网页上填的的 供自己手机测试的签名不对
    	if (resp.getType()==ConstantsAPI.COMMAND_SENDAUTH  && resp.errCode==BaseResp.ErrCode.ERR_OK)
	    {
    		SendAuth.Resp r = (SendAuth.Resp)resp;
    		String token = r.token;
    		openId = null;
    		this.furl = ("https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ APP_ID + "&secret="+ APP_Se +"&code=" + token + "&grant_type=authorization_code");
    		TT tt = new TT();               //好了 先通过http请求获取access_token 和  openID
    		tt.start();	      
	    } 
    }
    

    public class TT extends Thread {    //向微信服务器发http请求
    	public void run() {
    		String urlget=furl;
    		a_t_r="";
    		try {
    			URL url = new URL(urlget);
    			HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
    			httpURLConnection.setDoOutput(true);
    			httpURLConnection.setDoInput(true);
    			httpURLConnection.setConnectTimeout(10000);
    			httpURLConnection.setRequestMethod("GET");
    			httpURLConnection.connect();  
    			InputStreamReader bis = new InputStreamReader(httpURLConnection.getInputStream(),"utf-8");
    			int c = 0;
    			while((c = bis.read()) != -1){        
    				a_t_r=a_t_r+(char)c;   
    			}
    		}catch (Exception e) {
    			System.out.println(urlget + "  HTTP通信失败");
    			a_t_r = "http error";
    		}
    		if (a_t_r!="http error"){	
    			
    			if(openId == null)            //json暂时都是在unity中解开....  这里是调用unity解http回应的json
    				UnityPlayer.UnitySendMessage("Canvas","json_AcToken",a_t_r);            
    			else 
    				UnityPlayer.UnitySendMessage("Canvas","json_UserInfo",a_t_r);
    		}
    	}    
    }
    
    public void GetUserInfoReq(String ac_token, String openID){             //unity 解 出access_token , 和 openID 后找微信服务器拉用户信息
    	openId = openID;
    	this.furl = "https://api.weixin.qq.com/sns/userinfo?access_token="+ ac_token + "&openid=" + openID;
    	TT tt = new TT();
		tt.start();	 
    }
    
    public static int GetNetype(Context context)  
	{   
	    int netType = -1;    
	    ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);   
	    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();   
	    if(networkInfo==null)  {   
	        return netType;   
	    }   
	    int nType = networkInfo.getType();   
	    if(nType==ConnectivityManager.TYPE_MOBILE) {   
	        if(networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {   //移动联通
	            netType = 3;   
	        }   
	        else {   
	            netType = 2;   
	        }   
	    }   
	    else if(nType==ConnectivityManager.TYPE_WIFI) {   
	        netType = 1;   
	    }   
	    return netType;   
	}  

    public Bitmap Bytes2Bimap(byte[] b) {         
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);  
        } else {  
            return null;  
        }  
    }  
    public float lowBattery(){           
    	return -50; 	
    }
    @TargetApi(21)
    public float highBattery(){       
    	BatteryManager batteryManager=(BatteryManager)getSystemService(BATTERY_SERVICE);
    	return (float)((batteryManager.getIntProperty(4)+0.0) / 100); 	
    }
}



值得一提的是 授权后需要的http请求, 还有json的解析, 既可以写在unity中也可以写在SDK中,

这里我图方便, 刚好unity中有json类, SDK中有http类, 所以我一个写在unity中 一个写在SDK中

当然这都不是正确的作法, 出于安全考虑 app_secret,access_token等信息不应该暴露在客户端中, 所以对应的http请求应该在服务器上进行。


猜你喜欢

转载自blog.csdn.net/AXuan_K/article/details/60780370