美文网首页Android 三方集成Android
Android 三方使用之微信登录,微信分享,微信分享图片,支付

Android 三方使用之微信登录,微信分享,微信分享图片,支付

作者: 没有了遇见 | 来源:发表于2021-11-17 17:21 被阅读0次

近年来三方导流,方便用户使用App,以及方便App数据分享越来越多的App支持了三方登录以及三方分享网页和图片.在此,整理了一系列三方库的集成方法以及集成中遇到的问题


微信三方

一,微信配置

1:说明文档

   文档 :  https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Access_Guide/Android.html

2.资源引用

  implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'

3.微信AndroidManifest.xml配置

 <activity
        android:name=".wxapi.WXEntryActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:taskAffinity="com.mango.voaenglish"
        android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />

    <activity
        android:name=".wxapi.WXPayEntryActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen" />

注意!!!

A:WXEntryActivity,WXPayEntryActivity所处的包名必须在

image.png

B:微信的回掉现在不区分成功和取消(微信SDK的问题)

C:新版本微信可能没有province或者country 请仔细查阅文档做适配

二,微信三方使用

1:微信登录

1.第一步

  //登录微信
fun loginWechat(mContext: Context) {
    if (isWXAppInstalledAndSupported(mContext)) {
        Thread {
            val req = SendAuth.Req()
            req.scope = "snsapi_userinfo"
            req.state = ""
            val iwxapi = WXAPIFactory.createWXAPI(mContext, APP_WECHAT_KEY, true)
            iwxapi.registerApp(APP_WECHAT_KEY)
            iwxapi.sendReq(req)
        }.start()
    } else {
    }
}

2.回调获取数据

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

private IWXAPI api;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    api = WXAPIFactory.createWXAPI(this, Constant.INSTANCE.getAPP_WECHAT_KEY(), false);
    api.handleIntent(getIntent(), this);
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
    api.handleIntent(intent, this);
}

@Override
public void onReq(BaseReq baseReq) {
}


private SendAuth.Resp resp;

@Override
public void onResp(BaseResp baseResp) {

    //微信登录为getType为1,分享为0
    if (baseResp.getType() == 1) {
        //登录回调
        resp = (SendAuth.Resp) baseResp;
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                String code = String.valueOf(resp.code);
                //获取用户信息
                ThirdUtil.INSTANCE.getAccessToken(code);
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED://用户拒绝授权
                showMessage("用户拒绝授权");
                this.finish();
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                showMessage( "用户取消绑定");
                this.finish();
                break;
            default:
                this.finish();
                break;
        }
    }else if (baseResp.getType()==ConstantsAPI.COMMAND_PAY_BY_WX){
        String result = "";
        switch (baseResp.errCode) {
            case BaseResp.ErrCode.ERR_OK:
                result = "支付成功";

                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "支付取消";
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "支付失败";
                break;
            default:
                result = "支付失败";
                break;
        }
        showMessage( result);
        this.finish();

    }else {
        String result = "";
        switch (baseResp.errCode) {
            //现阶段 取消分享以及分享成功默认返回的都是分享成功 逻辑需求请注意
            case BaseResp.ErrCode.ERR_OK:
                result = "分享成功";
                break;
            case BaseResp.ErrCode.ERR_USER_CANCEL:
                result = "分享取消";
                break;
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
                result = "分享失败";
                break;
            default:
                result = "分享失败";
                break;
        }
        showMessage(result);
        this.finish();
    }


}

private  void showMessage(String message){
    Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
}
获取数据
//获取用户token
fun getAccessToken(code: String) {
    val getTokenUrl = String.format(
        "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=%s&secret=%s&code=%s&grant_type=authorization_code", APP_WECHAT_KEY,
        APP_WECHAT_SERECT, code
    )
    val resultCallback: OkHttpUtils.ResultCallback<String> =
        object : OkHttpUtils.ResultCallback<String>() {
            override fun onSuccess(response: String) {
                var openId: String? = null
                try {
                    val jsonObject = JSONObject(response)
                    access = jsonObject.getString("access_token")
                    openId = jsonObject.getString("openid")
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
                getWechatUserInfo(openId)
            }

            override fun onFailure(e: java.lang.Exception) {
                // todo 异常处理
            }
        }
    OkHttpUtils.get(getTokenUrl, resultCallback)
}
    
 //获取微信用户信息
private fun getWechatUserInfo(openId: String?) {

    //获取个人信息
    val getUserInfo =
        "https://api.weixin.qq.com/sns/userinfo?access_token=$access&openid=$openId"
    val resultCallback: OkHttpUtils.ResultCallback<WeChatInfo> =
        object : OkHttpUtils.ResultCallback<WeChatInfo>() {
            override fun onSuccess(response: WeChatInfo) {
                response.errCode = response.errCode
                response.accessToken = access
                //获取到微信用户信息
                if (response != null) WechatLoginObservable.getInstance().update(response)
            }

            override fun onFailure(e: java.lang.Exception) {
                // todo 异常处理
            }
        }
    OkHttpUtils.get(getUserInfo, resultCallback)
}

2:分享网页

  //微信分享
fun shareWechat(
    mContext: Context,
    url: String,
    title: String,
    desc: String,
    thumbBmp: Bitmap?
) {
    var webpage = WXWebpageObject()
    val api = WXAPIFactory.createWXAPI(mContext, Constant.APP_WECHAT_KEY)
    //长度小于 10240
    webpage.webpageUrl = url
    //分享的内容
    var msg = WXMediaMessage(webpage)
    //长度限制 512
    msg.title = title
    //长度限制 1024
    msg.description = desc
    //byty[] 限制 65536 预览图
    msg.setThumbImage(thumbBmp)
    val req = SendMessageToWX.Req()
    req.message = msg
    //分享类型
    req.scene = SendMessageToWX.Req.WXSceneSession
    api.sendReq(req) //发送到微信
}

3.分享图片

    fun shareWechatImg(mContext: Context, bmp: Bitmap?) {

    val api = WXAPIFactory.createWXAPI(mContext, Constant.APP_WECHAT_KEY)
    //初始化 WXImageObject 和 WXMediaMessage 对象
    val imgObj = WXImageObject(bmp)
    val msg = WXMediaMessage()

    msg.mediaObject = imgObj
    val thumbBmp = Bitmap.createScaledBitmap(bmp!!, 120, 120, true)
    bmp.recycle()
    // 限制 65536 预览图
    msg.thumbData = Util.bmpToByteArray(thumbBmp, true)


    //构造一个Req

    //构造一个Req
    val req = SendMessageToWX.Req()
    req.transaction = buildTransaction("img")
    req.message = msg
    req.scene = SendMessageToWX.Req.WXSceneSession

    //调用api接口,发送数据到微信
    api.sendReq(req)
}

fun buildTransaction(type: String?): String? {
    return if (type == null) System.currentTimeMillis()
        .toString() else type + System.currentTimeMillis()
}

4.微信支付

  //微信支付 数据需要后台生成预订单的时候返回支付的数据(放后台做前端不做)
fun payWechat(
    mContext: Context,
    appId: String,
    partnerId: String,
    prepayId: String,
    nonceStr: String,
    timeStamp: String,
    packageValue: String,
    sign: String,
    extData: String
) {
    var api = WXAPIFactory.createWXAPI(mContext, Constant.APP_WECHAT_KEY);
    api.registerApp(Constant.APP_WECHAT_KEY)

    var req = PayReq()
    req.appId = appId
    req.partnerId = partnerId
    req.prepayId = prepayId
    req.nonceStr = nonceStr
    req.timeStamp = timeStamp
    req.packageValue = "Sign=WXPay"
    req.sign = sign
    req.extData = extData
    api.sendReq(req)
}

总结:

三方库简单的集成以及主要功能实现,以此记录,欢迎问题探讨,来都来了点个赞再走吧!!!

1.Android 三方使用之QQ登录,QQ图片分享,QQ分享网页

2.源码地址

相关文章

网友评论

    本文标题:Android 三方使用之微信登录,微信分享,微信分享图片,支付

    本文链接:https://www.haomeiwen.com/subject/zboltrtx.html