本章适用刚入门小白,手把手教你直调微信SDK。

1.接上文,上个文章。服务器我们已经搭建好了,现在我们接入微信功能

2.准备微信开放平台申请的APPID,用于注册实例化。

3.创建项目工程,工程包名和微信开放平台申请的应用包名必须一致,包名不一致调不起微信SDK功能

4.在android studio 导入微信SDK Gradle依赖   在build.gradle中导入

dependencies {
    api 'com.tencent.mm.opensdk:wechat-sdk-android:+'//    导入Wechat SDK依赖库
}

5.视图层XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/btnLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="微信授权" />

    <Button
        android:id="@+id/btnShare"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="微信分享" />

    <Button
        android:id="@+id/btnPay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="微信支付" />
</LinearLayout>

6.创建业务层

/**
 * 微信业务层
 * @author liaozan8888@163.com
 */
public class WeChatService {

    //APPID
    public static final String APP_ID = "填写微信开放平台应用申请的APPID";

    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI iwxapi;

    private static WeChatService instance;
    /**
     * 实例化
     */
    public static WeChatService GetInstance(){
        if(instance==null){
            instance = new WeChatService();
        }
        return instance;
    }
    /**
     * 初始化
     */
    private WeChatService() {
        // 通过WXAPIFactory工厂,获取IWXAPI的实例
        iwxapi = WXAPIFactory.createWXAPI(MainActivity.Instance, APP_ID, false);
        iwxapi.registerApp(APP_ID);// 将该app注册到微信
    }

    /**
     * 微信登陆
     */
    public void openWeChatLogin(){
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk";
        //调起微信接口
        iwxapi.sendReq(req);
    }
    /**
     * 调起微信支付
     * @param appId
     * @param partnerId
     * @param prepayId
     * @param nonceStr
     * @param timeStamp
     * @param sign
     */
    public void openWeChatPay(String appId,String partnerId,String prepayId,String nonceStr,String timeStamp,String sign){
        //支付请求类
        PayReq request = new PayReq();
        request.appId = appId;
        request.partnerId =partnerId;
        request.prepayId= prepayId;
        request.packageValue = "Sign=WXPay";
        request.nonceStr= nonceStr;
        request.timeStamp= timeStamp;
        request.sign=sign;
        //调起微信支付
        iwxapi.sendReq(request);
    }

    /**
     * 调起微信分享 (h5链接分享)
     * @param title
     * @param description
     * @param scene 分享场景 Session微信好友  Timeline朋友圈
     */
    public  void openWeChatShare(String title,String description,String scene){
        //初始化一个WXWebpageObject,填写url
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl ="http://cms.iclickdesign.com/shareWx.html";
        //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        msg.description = description;
        //链接压缩图
        //Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.drawable.send_music_thumb);
        //msg.thumbData =Util.bmpToByteArray(thumbBmp, true);
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.message =msg;
        //分享场景
        if(scene.equals("Session")){
            req.scene = SendMessageToWX.Req.WXSceneSession ;
        }else if(scene.equals("Timeline")){
            req.scene = SendMessageToWX.Req.WXSceneTimeline ;
        }
        //调用 api 接口,发送数据到微信
        iwxapi.sendReq(req);
    }
}

7.微信分享、微信授权回调监听,在工程下创建wxapi.WXEntryActivity类  继承Activity类  实现IWXAPIEventHandler接口

/**
 * 微信分享登陆回调监听
 * @author liaozan8888@163.com
 */
public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    //实例化业务层
    private WeChatService wechatService = WeChatService.GetInstance();

    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI iwxapi;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //实例化
        iwxapi = WXAPIFactory.createWXAPI(this, WeChatService.APP_ID);
        iwxapi.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        switch (baseReq.getType()){

        }
    }
    //第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
    @Override
    public void onResp(BaseResp baseResp) {
        switch (baseResp.getType()){
            case ConstantsAPI.COMMAND_SENDAUTH: //授权回调
                break;
            case ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX://分享回调
                break;
        }
        finish();
    }
}

8.微信支付回调监听  在工程中创建wxapi.WXPayEntryActicity类 继承Activity类  实现IWXAPIEventHandler接口

/**
 * 微信回调监听
 * @author liaozan8888@163.com
 */
public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {

    //实例化业务层
    private WeChatService wechatService = WeChatService.GetInstance();

    // IWXAPI 是第三方app和微信通信的openapi接口
    private IWXAPI iwxapi;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iwxapi = WXAPIFactory.createWXAPI(this, WeChatService.APP_ID);
        iwxapi.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        switch (baseReq.getType()){

        }
    }
    //第三方应用发送到微信的请求处理后的响应结果,会回调到该方法
    @Override
    public void onResp(BaseResp baseResp) {
        switch (baseResp.getType()){
            case ConstantsAPI.COMMAND_PAY_BY_WX: //支付回调
                break;
        }
        finish();
    }
}

9.在AndroidManifest.xml中注册微信回调Activity、权限配置、引用查询库

    <!--    权限配置-->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <!--引用查询包下类-->
    <queries>
        <package android:name="com.tencent.mm" />
    </queries>
    
    
    <!-- 在application标签下编写activity -->
    <!--注册回调Activity-->
    <activity
        android:name=".wxapi.WXEntryActivity"
        android:exported="true"
        android:launchMode="singleTop"/>
    <activity
        android:name=".wxapi.WXPayEntryActivity"
        android:exported="true"
        android:launchMode="singleTop"/>

10.启动类

public class MainActivity extends AppCompatActivity {

    public static MainActivity Instance;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Instance = this;
        //微信授权事件
        findViewById(R.id.btnLogin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WeChatService.GetInstance().openWeChatLogin();
            }
        });
        //微信分享事件
        findViewById(R.id.btnShare).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WeChatService.GetInstance().openWeChatShare("测试","测试","Session");
            }
        });
        //微信支付事件
        findViewById(R.id.btnPay).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WeChatService.GetInstance().openWeChatPay("xxx","xxx"
                ,"xxx"
                ,"xxx"
                ,"xxx"
                ,"xxx");
            }
        });
    }
}

11.工程包类结构

GitHub仓库链接:https://github.com/Lz-Yonnw/WeChat_App.git

发送到微信的请求处理响应结构  会回调到该方法(onResp),具体回调处理逻辑请根据当前业务场景实现。

完结  望对你有所帮助!下期出iOS接入微信支付

 

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐