phonegap 微信登录总结

wechat.js文件
cordova.define(“com.libei.cordova.wechat.Wechat”, function(require, exports, module) { var exec = require(‘cordova/exec’);

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
 * 
 * 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);
 * });
 * 
 */
share: function (message, onSuccess, onError) {
    exec(onSuccess, onError, "Wechat", "share", [message]);
},

/**
 * Sending an auth request to Wechat
 *
 * @example
 * 
 * Wechat.auth(function (response) { alert(response.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
 * 
 * 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);
 * });
 * 
 */
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() {

        @Override
        public void onResponse(String response) {
            try {
                JSONObject obj = new JSONObject(response);
                String openid1=(String) obj.get("openid");
                RSACoder RSA = new RSACoder();
                Map 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);



}







}

你可能感兴趣的:(phonegap,phonegap,微信,微信登录)