Cocos项目中接入微信SDK

前端之家收集整理的这篇文章主要介绍了Cocos项目中接入微信SDK前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1.做好微信开放平台的审核工作

第一步:创建自己的微信开放平台账号并且提交自己的应用等待审核

审核通过之后就会如上图所示,审核已通过。一般应用审核通过之后只会有微信分享和收藏的功能


某些接口是要收费的,具体要看自己的需求了,再提交应用的时候有很重要的两点,第一就是包名,安卓程序唯一标识就是包名,也是安装在手机上的唯一标识,这样系统才会识别出来这是两种不同的应用。还有一个就是应用签名:把apk文件装在手机上用微信开放平台的签名检测工具,输入自己的包名就可以得出应用签名了,然后把这个签名提交到微信开放平台上。(这里有一点需要特别注意,到后面出现无法登陆微信的情况很有可能是本地签名和微信开放平台的签名不一致所导致的,导出自己的apk时,要注意需要用keystore文件来对apk进行签名,这样带有keystore文件的apk以后就可以用这个keystore来签名了,尽量不要用debug.keystore。在以后微信开放平台上面的应用签名也可以修改

在eclipse里面打开这个窗口进行keystore的导入(首先要自己创建一个keystore文件):



选择keystore文件之后点击apply,然后ok就可以了。


2.编写本地代码

由于我的项目是Cocos项目,要想调用Java层的微信SDK接口必须在本地编写逻辑代码,然后借助Jni来调用Java层的代码
  1. self.Button_login:addTouchEventListener(function ( sender,eventType )
  2. if eventType == ccui.TouchEventType.ended then
  3. print('==================登录 LoginScene:btnEvent()')
  4. self:lodingAnimation()
  5. game.anysdk:login_native()
  6. end
  7. end)

然后走到anysdk:login_native里面(也可以直接走到Jni里面)

  1. function AnySdk:login_native()
  2. local function LoginServer()
  3. local function callBack()
  4. MissionManager.getMission('login_mission','main_mission'):sendData(MDM_GR_logoN,SUB_GP_logoN_ACCOUNTS)
  5. end
  6. MissionManager.connect(LOGIN_SERVER_NAME,LOGIN_SERVER_IP,LOGIN_SERVER_PORT,callBack)
  7. end
  8.  
  9. if device.platform == "android" or device.platform == "ios" then
  10. local access_token = cc.UserDefault:getInstance():getStringForKey("access_token","")
  11. local openid = cc.UserDefault:getInstance():getStringForKey("openid","")
  12. if access_token ~= "" and openid ~= "" then
  13. self:getWeixinInfo(access_token,openid,LoginServer)
  14. else
  15. JniFun:create():longinWX(APP_ID,AppSecret)
  16. end
  17. else
  18. --self:getWeixinInfo("","",LoginServer)
  19. local function callBack()
  20. MissionManager.getMission('login_mission',SUB_GP_REGISTER_ACCOUNTS)
  21. end
  22. MissionManager.connect(LOGIN_SERVER_NAME,callBack)
  23. end
  24. end

然后进入到JniFun:loginWX里面:

  1. #include "JniFun.h"
  2. #include "cocos2d.h"
  3.  
  4. #include "CCLuaEngine.h"
  5.  
  6. #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
  7. #include <Jni.h>
  8. #include "platform/android/jni/JniHelper.h"
  9. #include "jubaosdk/ShellApiJni.h"
  10. #endif
  11. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  12. #include "IosHelper.h"
  13. #endif
  14.  
  15. #define JAVA_CLASSNAME "com/wx/Native"
  16. using namespace cocos2d;
  1. void JniFun::longinWX(const char* APP_ID,const char* AppSecret)
  2. {
  3. #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
  4. JniMethodInfo minfo;
  5. bool isHave = JniHelper::getStaticMethodInfo(minfo,JAVA_CLASSNAME,"LoginWX","(Ljava/lang/String;Ljava/lang/String;)V");
  6. if (isHave)
  7. {
  8. jstring jAPP_ID = minfo.env->NewStringUTF(APP_ID);
  9. jstring jAppSecret = minfo.env->NewStringUTF(AppSecret);
  10. minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID,jAPP_ID,jAppSecret);
  11.  
  12. minfo.env->DeleteLocalRef(jAPP_ID);
  13. minfo.env->DeleteLocalRef(jAppSecret);
  14. minfo.env->DeleteLocalRef(minfo.classID);
  15. cocos2d::log("JniFun call LoginWX over!");
  16. }
  17. else
  18. {
  19. //NoticeMsg::Instance().Showlogon(false);
  20. cocos2d::log("JniFun call LoginWX error!");
  21. }
  22. #endif
  23. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  24. cocos2d::log("IosHelper::sendAuthRequest!");
  25. IosHelper::sendAuthRequest();
  26. #endif
  27. }

在JniFun里面就用到了cocos封装好的JniHelper类,通过上面的代码才会真正调用到Java里面的微信API方法

其中这里需要注意,微信的方法编写是有约束的,打个比方,如果你的项目包名是com.zhijiegame.www,那么你就要在src下面先新建一个com.zhijiegame.www.wxapi的包,这个命名规则是微信要求的,然后在这个包下面创建一个WXEntryAvtivity的类:
  1. package com.ydqp.yjmj.wxapi;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.net.URL;
  8.  
  9. import android.app.Activity;
  10. import android.content.Context;
  11. import android.content.Intent;
  12. import android.content.res.AssetManager;
  13. import android.graphics.Bitmap;
  14. import android.graphics.BitmapFactory;
  15. import android.os.Bundle;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.view.WindowManager;
  19. import android.widget.Button;
  20. import android.widget.Toast;
  21.  
  22. import com.wx.Native;
  23. import com.wx.Util;
  24.  
  25.  
  26. import com.tencent.mm.sdk.constants.ConstantsAPI;
  27. import com.tencent.mm.sdk.modelbase.BaseReq;
  28. import com.tencent.mm.sdk.modelbase.BaseResp;
  29. import com.tencent.mm.sdk.modelmsg.SendAuth;
  30. import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
  31. import com.tencent.mm.sdk.modelmsg.ShowMessageFromWX;
  32. import com.tencent.mm.sdk.modelmsg.WXAppExtendObject;
  33. import com.tencent.mm.sdk.modelmsg.WXImageObject;
  34. import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
  35. import com.tencent.mm.sdk.modelmsg.WXTextObject;
  36. import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
  37. import com.tencent.mm.sdk.openapi.IWXAPI;
  38. import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
  39. import com.tencent.mm.sdk.openapi.WXAPIFactory;
  40.  
  41. public class WXEntryActivity extends Activity implements IWXAPIEventHandler{
  42. public static String Tag = "YZH";
  43. private static final int TIMELINE_SUPPORTED_VERSION = 0x21020001;
  44. private static WXEntryActivity sContext = null;
  45. public static boolean blogonWX = false;
  46. public static boolean isShareWX = false;
  47. public static boolean isShareURL = false;
  48. private static final int THUMB_SIZE = 150;
  49.  
  50. public static final String APP_ID = "*****************************";
  51. public static final String AppSecret = "******************************";
  52. private IWXAPI api;
  53. private static final int SceneSession = 0;
  54. private static final int SceneTimeline = 1;
  55. public static String ReqWxLogin = "ReqWxLogin";
  56. public static String ReqWxShareImg = "ReqWxShareImg";
  57. public static String ReqWxShareTxt = "ReqWxShareTxt";
  58. public static String ReqWxShareUrl = "ReqWxShareUrl";
  59. public static String ReqWXPay = "ReqWXPay";
  60. public void onCreate(Bundle savedInstanceState)
  61. {
  62. super.onCreate(savedInstanceState);
  63. sContext = this;
  64. Log.d(Tag,"onCreate");
  65. Log.d(Tag,"onCreate1");
  66. Intent intent = getIntent();
  67. Log.d(Tag,"onCreate2");
  68. api = WXAPIFactory.createWXAPI(this,APP_ID,false);
  69. Log.d(Tag,"onCreate3");
  70. api.registerApp(APP_ID);
  71. Log.d(Tag,"onCreate4");
  72. api.handleIntent(intent,this);
  73. Log.d(Tag,"onCreate5");
  74. if (intent.hasExtra(ReqWxLogin))
  75. {
  76. reqLogin();
  77. }
  78. else if(intent.hasExtra(ReqWxShareImg))
  79. {
  80. isShareWX=true;
  81. Log.d(Tag,"ReqWxShareImg");
  82. String ImgPath = intent.getStringExtra("ImgPath");
  83. int nType = intent.getIntExtra("ShareType",0);
  84. reqShareImg(ImgPath,nType);
  85. }
  86. else if(intent.hasExtra(ReqWxShareTxt))
  87. {
  88. isShareWX=true;
  89. Log.d(Tag,"ReqWxShareTxt");
  90. String ShareText = intent.getStringExtra("ShareText");
  91. int nType = intent.getIntExtra("ShareType",0);
  92. reqShareTxt(ShareText,nType);
  93. }
  94. else if(intent.hasExtra(ReqWxShareUrl))
  95. {
  96. isShareWX=true;
  97. Log.d(Tag,"ReqWxShareUrl");
  98. String ShareUrl = intent.getStringExtra("ShareUrl");
  99. String ShareTitle = intent.getStringExtra("ShareTitle");
  100. String ShareDesc = intent.getStringExtra("ShareDesc");
  101. int nType = intent.getIntExtra("ShareType",0);
  102. reqShareUrl(ShareUrl,ShareTitle,ShareDesc,nType);
  103. }
  104. Log.d(Tag,"onCreate fnish");
  105. finish();
  106. }
  107. @Override
  108. protected void onNewIntent(Intent intent)
  109. {
  110. super.onNewIntent(intent);
  111. Log.d(Tag,"1");
  112. setIntent(intent);
  113. Log.d(Tag,"2");
  114. api.handleIntent(intent,"3");
  115. }
  116. public void reqLogin()
  117. {
  118. SendAuth.Req req = new SendAuth.Req();
  119. req.scope = "snsapi_userinfo";
  120. req.state = "123";
  121. api.sendReq(req);
  122. Log.d(Tag,"reqLogin");
  123. if(!api.openWXApp())
  124. {
  125. Toast.makeText(this,"请先安装微信客户端",Toast.LENGTH_LONG).show();
  126. }
  127. }
  128. public void reqShareImg(String ImgPath,int nType)
  129. {
  130. File file = new File(ImgPath);
  131. if (!file.exists())
  132. {
  133. Log.d(Tag,"reqShare file not exists:"+ImgPath);
  134. return;
  135. }
  136.  
  137. Bitmap bmp = BitmapFactory.decodeFile(ImgPath);
  138. WXImageObject imgObj = new WXImageObject(bmp);
  139. WXMediaMessage msg = new WXMediaMessage();
  140. msg.mediaObject = imgObj;
  141. Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp,128,72,true);
  142. bmp.recycle();
  143. msg.thumbData = Util.bmpToByteArray(thumbBmp,true);
  144. SendMessageToWX.Req req = new SendMessageToWX.Req();
  145. req.transaction = buildTransaction("img");
  146. req.message = msg;
  147. if(nType==SceneTimeline )
  148. {
  149. req.scene = SendMessageToWX.Req.WXSceneTimeline;
  150. }
  151. else if(nType==SceneSession )
  152. {
  153. req.scene = SendMessageToWX.Req.WXSceneSession;
  154. }
  155. api.sendReq(req);
  156. Log.d(Tag,"reqShare Ok:"+ImgPath);
  157. }
  158. public void reqShareTxt(String text,int nType)
  159. {
  160. WXTextObject textObj = new WXTextObject();
  161. textObj.text = text;
  162.  
  163. WXMediaMessage msg = new WXMediaMessage();
  164. msg.mediaObject = textObj;
  165. // msg.title = "Will be ignored";
  166. msg.description = text;
  167.  
  168. SendMessageToWX.Req req = new SendMessageToWX.Req();
  169. req.transaction = buildTransaction("text");
  170. req.message = msg;
  171. if(nType==SceneTimeline )
  172. {
  173. req.scene = SendMessageToWX.Req.WXSceneTimeline;
  174. }
  175. else if(nType==SceneSession )
  176. {
  177. req.scene = SendMessageToWX.Req.WXSceneSession;
  178. }
  179. api.sendReq(req);
  180.  
  181. Log.d(Tag,"reqShareTxt Ok:"+text);
  182. }
  183. public native void Share();
  184. public void reqShareUrl(String url,String title,String desc,int nType)
  185. {
  186. WXWebpageObject textObj = new WXWebpageObject();
  187. textObj.webpageUrl = url;
  188.  
  189. WXMediaMessage msg = new WXMediaMessage();
  190. msg.mediaObject = textObj;
  191. msg.title = title;
  192. msg.description = desc;
  193. //if(nType==SceneTimeline )
  194. {
  195. AssetManager asm=getAssets();
  196. String s = "weixin_share_icon.png";
  197. InputStream is = null;
  198. try {
  199. is = asm.open(s);
  200. } catch (IOException e) {
  201. // TODO Auto-generated catch block
  202. e.printStackTrace();
  203. }//asm.open("");
  204.  
  205. Bitmap bmp=BitmapFactory.decodeStream(is);
  206. URL res = this.getClass().getResource("icon.png");
  207. Log.d(Tag,"r:"+res);
  208. if (null != bmp) {
  209. Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp,80,true);
  210. bmp.recycle();
  211. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  212. thumbBmp.compress(Bitmap.CompressFormat.PNG,100,baos);
  213. msg.thumbData = baos.toByteArray();
  214. }
  215. }
  216. SendMessageToWX.Req req = new SendMessageToWX.Req();
  217. req.transaction = buildTransaction("webpage");
  218. req.message = msg;
  219. if(nType==SceneTimeline )
  220. {
  221. isShareURL = false;
  222. req.scene = SendMessageToWX.Req.WXSceneTimeline;
  223. }
  224. else if(nType==SceneSession )
  225. {
  226. isShareURL = false;
  227. req.scene = SendMessageToWX.Req.WXSceneSession;
  228. }
  229. api.sendReq(req);
  230.  
  231. Log.d(Tag,"reqShareUrl Ok:"+url);
  232. }
  233.  
  234. public void reqShareTxtCB(String text,int nType)
  235. {
  236. // send appdata with no attachment
  237. WXAppExtendObject appdata = new WXAppExtendObject("lallalallallal","filePath");
  238. boolean bValue = appdata.checkArgs();
  239. if (!bValue)
  240. {
  241. Log.d(Tag,"reqShareTxtCB Error:"+text);
  242. }
  243. WXMediaMessage msg = new WXMediaMessage();
  244. msg.title ="11";
  245. msg.description = "22";
  246. msg.mediaObject = appdata;
  247. SendMessageToWX.Req req = new SendMessageToWX.Req();
  248. req.transaction = buildTransaction("appdata");
  249. req.message = msg;
  250. if(nType==SceneTimeline )
  251. {
  252. req.scene = SendMessageToWX.Req.WXSceneTimeline;
  253. }
  254. else if(nType==SceneSession )
  255. {
  256. req.scene = SendMessageToWX.Req.WXSceneSession;
  257. }
  258. api.sendReq(req);
  259.  
  260. Log.d(Tag,"reqShareTxtCB Ok:"+text);
  261. }
  262. @Override
  263. public void onReq(BaseReq req)
  264. {
  265. switch (req.getType())
  266. {
  267. case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
  268. Log.d(Tag,"onReq:COMMAND_GETMESSAGE_FROM_WX");
  269. break;
  270. case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
  271. Log.d(Tag,"onReq:COMMAND_SHOWMESSAGE_FROM_WX");
  272. break;
  273. default:
  274. break;
  275. }
  276.  
  277. Log.d(Tag,"onReq:"+req.getType());
  278. }
  279.  
  280. @Override
  281. public void onResp(BaseResp resp) {
  282. String result = null;
  283.  
  284. Log.d(Tag,"errCode:"+resp.errCode);
  285. switch (resp.errCode) {
  286. case BaseResp.ErrCode.ERR_OK:
  287. Log.d(Tag,"OK");
  288. result = "操作成功";
  289. if(!isShareWX)
  290. {
  291. isShareWX=!isShareWX;
  292. result ="操作成功";
  293. String code = ((SendAuth.Resp) resp).code;
  294. String Url =code;
  295. Log.d(Tag,"OK1");
  296. Log.d(Tag,Url);
  297. Native.WxLoginGetAccessToken(Url);
  298. Log.d(Tag,"OK2");
  299. }
  300. Log.d(Tag,"Start Share");
  301. if(isShareURL)
  302. {
  303. Log.d(Tag,"Shareing");
  304. Share();
  305. result ="分享成功";
  306. }
  307. Log.d(Tag,"Over Share");
  308. break;
  309. case BaseResp.ErrCode.ERR_USER_CANCEL:
  310. Log.d(Tag,"quxiao");
  311. result ="用户取消";
  312. Native.WxLoginGetAccessToken("ERR_USER_CANCEL");
  313. break;
  314. case BaseResp.ErrCode.ERR_AUTH_DENIED:
  315. Log.d(Tag,"jujue");
  316. result ="用户拒绝";
  317. Native.WxLoginGetAccessToken("ERR_AUTH_DENIED");
  318. break;
  319. default:
  320. Log.d(Tag,"buzhidao");
  321. result ="未知错误";
  322. Native.WxLoginGetAccessToken("REE_Unknow");
  323. break;
  324. }
  325. Toast.makeText(this,result,Toast.LENGTH_LONG).show();
  326. }
  327. private String buildTransaction(final String type) {
  328. return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
  329. }
  330. }
把你申请得到的APP_ID和AppSecret填上去,就可以了,这里只是做了简单的登录功能,其他部分都差不多,调用不同的函数就可以了。

猜你在找的Cocos2d-x相关文章