phonegap 위챗 로그인 요약
module.exports = {Scene: {SESSION: 0,//채팅창 TIMELINE: 1,//모멘트 FAVORITE: 2//즐겨찾기},
Type: {
APP: 1,
EMOTION: 2,
FILE: 3,
IMAGE: 4,
MUSIC: 5,
VIDEO: 6,
WEBPAGE: 7
},
isInstalled: function (onSuccess, onError) {
exec(onSuccess, onError, "Wechat", "isWXAppInstalled", []);
},
/**
* Share a message to wechat app
*
* @example
* <code>
* Wechat.share({
* message: {
* title: "Message Title",
* description: "Message Description(optional)",
* mediaTagName: "Media Tag Name(optional)",
* thumb: "http://YOUR_THUMBNAIL_IMAGE",
* media: {
* type: Wechat.Type.WEBPAGE, // webpage
* webpageUrl: "https://github.com/xu-li/cordova-plugin-wechat" // webpage
* }
* },
* scene: Wechat.Scene.TIMELINE // share to Timeline
* }, function () {
* alert("Success");
* }, function (reason) {
* alert("Failed: " + reason);
* });
* </code>
*/
share: function (message, onSuccess, onError) {
exec(onSuccess, onError, "Wechat", "share", [message]);
},
/**
* Sending an auth request to Wechat
*
* @example
* <code>
* Wechat.auth(function (response) { alert(response.code); });
* </code>
*/
auth: function (scope, state, onSuccess, onError) {
if (typeof scope == "function") {
// Wechat.auth(function () { alert("Success"); });
// Wechat.auth(function () { alert("Success"); }, function (error) { alert(error); });
return exec(scope, state, "Wechat", "sendAuthRequest");
}
if (typeof state == "function") {
// Wechat.auth("snsapi_userinfo", function () { alert("Success"); });
// Wechat.auth("snsapi_userinfo", function () { alert("Success"); }, function (error) { alert(error); });
return exec(state, onSuccess, "Wechat", "sendAuthRequest", [scope]);
}
return exec(onSuccess, onError, "Wechat", "sendAuthRequest", [scope, state]);
},
/**
* Send a payment request
*
* @link https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=9_1
* @example
* <code>
* var params = {
* mch_id: '10000100', // merchant id
* prepay_id: 'wx201411101639507cbf6ffd8b0779950874', // prepay id returned from server
* nonce: '1add1a30ac87aa2db72f57a2375d8fec', // nonce string returned from server
* timestamp: '1439531364', // timestamp
* sign: '0CB01533B8C1EF103065174F50BCA001', // signed string
* };
* Wechat.sendPaymentRequest(params, function () {
* alert("Success");
* }, function (reason) {
* alert("Failed: " + reason);
* });
* </code>
*/
sendPaymentRequest: function (params, onSuccess, onError) {
exec(onSuccess, onError, "Wechat", "sendPaymentRequest", [params]);
}
};
});
2 wechatLogin.js function wechatLogin () {//클라이언트의 위챗 설치 여부 판단
Wechat.isInstalled(function (installed) {
alert("Wechat installed: " + (installed ? "Yes" : "No"));
}, function (reason) {
alert("Failed: " + reason);
});
// code
var scope = "snsapi_userinfo";
var state = "###";
Wechat.auth(scope,state, function (openid) {
/*var obj = eval('(' + response + ')');
var access_token=obj.access_token;
var openid=obj.openid;*/
alert(openid);
// you may use response.code to get the access token.
//alert(JSON.stringify(response));
}, function (reason) {
alert("Failed: " + reason);
});
// code
/*var scope = "snsapi_userinfo";
var state = "###";
Wechat.auth(scope, state,function (response) {
var data=JSON.stringify(response)
//var obj = eval(‘(’ + data + ‘)’); //var code=obj.code;//you may use response.code to get the access token. alert(data);
}, function (reason) {
alert("Failed: " + reason);
});*/
} 3 EntryActivity_wxapi
package com.guwu.mai.wxapi;
import java.util.Map;
import org.json.JSONException; import org.json.JSONObject;
import xu.li.cordova.wechat.Wechat; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Base64; import android.util.Log;
import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.tencent.mm.sdk.constants.ConstantsAPI; import com.tencent.mm.sdk.modelbase.BaseReq; import com.tencent.mm.sdk.modelbase.BaseResp; import com.tencent.mm.sdk.modelmsg.SendAuth; import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;
/** * Created by [email protected] on 9/1/15. */ public class EntryActivity extends Activity implements IWXAPIEventHandler {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Wechat.wxAPI == null) {
startMainActivity();
} else {
Wechat.wxAPI.handleIntent(getIntent(), this);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
if (Wechat.wxAPI == null) {
startMainActivity();
} else {
Wechat.wxAPI.handleIntent(intent, this);
}
}
@Override
public void onResp(BaseResp resp) {
Log.d(Wechat.TAG, resp.toString());
if (Wechat.currentCallbackContext == null) {
startMainActivity();
return ;
}
switch (resp.errCode) {
case BaseResp.ErrCode.ERR_OK:
switch (resp.getType()) {
case ConstantsAPI.COMMAND_SENDAUTH:
//auth(resp); //break; try { //getAccessToken(((SendAuth.Resp) resp).code); auth(resp); } catch (Exception e) {
e.printStackTrace();
}
break;
case ConstantsAPI.COMMAND_PAY_BY_WX:
default:
Wechat.currentCallbackContext.success();
break;
}
break;
case BaseResp.ErrCode.ERR_USER_CANCEL:
Wechat.currentCallbackContext.error(Wechat.ERROR_USER_CANCEL);
break;
case BaseResp.ErrCode.ERR_AUTH_DENIED:
Wechat.currentCallbackContext.error(Wechat.ERROR_AUTH_DENIED);
break;
case BaseResp.ErrCode.ERR_SENT_FAILED:
Wechat.currentCallbackContext.error(Wechat.ERROR_SENT_FAILED);
break;
case BaseResp.ErrCode.ERR_UNSUPPORT:
Wechat.currentCallbackContext.error(Wechat.ERROR_UNSUPPORT);
break;
case BaseResp.ErrCode.ERR_COMM:
Wechat.currentCallbackContext.error(Wechat.ERROR_COMMON);
break;
default:
Wechat.currentCallbackContext.error(Wechat.ERROR_UNKNOWN);
break;
}
finish();
}
@Override
public void onReq(BaseReq req) {
finish();
}
protected void startMainActivity() {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setPackage(getApplicationContext().getPackageName());
getApplicationContext().startActivity(intent);
}
/* protected void auth(BaseResp resp) { SendAuth.Resp res = ((SendAuth.Resp) resp);
Log.d(Wechat.TAG, res.toString());
JSONObject response = new JSONObject();
try {
response.put("code", res.code);
response.put("state", res.state);
response.put("country", res.country);
response.put("lang", res.lang);
} catch (JSONException e) {
Log.e(Wechat.TAG, e.getMessage());
}
Wechat.currentCallbackContext.success(response);
}*/
// code
public void auth(BaseResp resp) {
SendAuth.Resp res = ((SendAuth.Resp) resp);
Log.d(Wechat.TAG, res.toString());
//JSONObject response = new JSONObject();
getAccessTokenAndUid(res.code);
}
// code openid access_token
public void getAccessTokenAndUid(String code){
RequestQueue mQuene=Volley.newRequestQueue(EntryActivity.this);
String AppId="*****";
String secret="*****";
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AppId+
"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
// ——Volley
StringRequest stringRequest=new StringRequest(0, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
String openid1=(String) obj.get("openid");
RSACoder RSA = new RSACoder();
Map<String, Object> keyMap = RSA.initKey();
//
byte[] publicKey = RSA.getPublicKey(keyMap);
//byte[] publicKey = b;
//
byte[] privateKey = RSACoder.getPrivateKey(keyMap);
byte[] code1 = RSACoder.encryptByPublicKey(openid1.getBytes(),
publicKey);
//
String openid=Base64.encodeToString(code1, Base64.DEFAULT);
Wechat.currentCallbackContext.success(openid);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Log.d("TAG",response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.e("TAG",error.getMessage(),error);
}
});
mQuene.add(stringRequest);
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Java 코드로 위챗 페이지 스크롤 방지 (핵심 코드)인터넷에서 페이지가 상단이나 하단으로 미끄러지는 것을 방지할 수 있는 회색 바탕을 찾았습니다. 다음은 핵심 코드를 여러분께 참고하도록 공유합니다! 내 핵심 코드: 상기 코드는 여러분께 소개해 드린 위챗 페이지의 스크...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.