Cocos项目中接入微信SDK

论坛 期权论坛 脚本     
匿名网站用户   2020-12-19 20:25   11   0

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. if device.platform == "android" or device.platform == "ios" then
  9. local access_token = cc.UserDefault:getInstance():getStringForKey("access_token", "")
  10. local openid = cc.UserDefault:getInstance():getStringForKey("openid", "")
  11. if access_token ~= "" and openid ~= "" then
  12. self:getWeixinInfo(access_token,openid,LoginServer)
  13. else
  14. JniFun:create():longinWX(APP_ID,AppSecret)
  15. end
  16. else
  17. --self:getWeixinInfo("", "", LoginServer)
  18. local function callBack()
  19. MissionManager.getMission('login_mission','main_mission'):sendData(MDM_GR_LOGON,SUB_GP_REGISTER_ACCOUNTS)
  20. end
  21. MissionManager.connect(LOGIN_SERVER_NAME,LOGIN_SERVER_IP,LOGIN_SERVER_PORT,callBack)
  22. end
  23. end

然后进入到JniFun:loginWX里面:

  1. #include "JniFun.h"
  2. #include "cocos2d.h"
  3. #include "CCLuaEngine.h"
  4. #if CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
  5. #include <Jni.h>
  6. #include "platform/android/jni/JniHelper.h"
  7. #include "jubaosdk/ShellApiJni.h"
  8. #endif
  9. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  10. #include "IosHelper.h"
  11. #endif
  12. #define JAVA_CLASSNAME "com/wx/Native"
  13. 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. minfo.env->DeleteLocalRef(jAPP_ID);
  12. minfo.env->DeleteLocalRef(jAppSecret);
  13. minfo.env->DeleteLocalRef(minfo.classID);
  14. cocos2d::log("JniFun call LoginWX over!");
  15. }
  16. else
  17. {
  18. //NoticeMsg::Instance().ShowLogon(false);
  19. cocos2d::log("JniFun call LoginWX error!");
  20. }
  21. #endif
  22. #if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
  23. cocos2d::log("IosHelper::sendAuthRequest!");
  24. IosHelper::sendAuthRequest();
  25. #endif
  26. }

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

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







分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:1136255
帖子:227251
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP