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


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

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

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

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




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

unity接微信androidSDK,一个供参考测试的Demo_第1张图片



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

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

jo.Call(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



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请求应该在服务器上进行。


你可能感兴趣的:(unity3D)