IWXAPI的使用,发布分享和支付

先贴微信文档的地址吧,一切照着文档来

https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12&index=2

 

再记录一下我是怎么做的

首先是在application类里面定义,我继承Application的类叫ApplicationXpClient

public static IWXAPI MSGAPI;
public static final String WX_APPID="xxxxxxxxxxxxxxxxxxx";//你的应用从官方网站申请到的合法appId

将该app注册到微信

        MSGAPI=WXAPIFactory.createWXAPI(applicationContext,WX_APPID,false);
        MSGAPI.registerApp(WX_APPID);

支付功能

        if(!ApplicationXpClient.MSGAPI.isWXAppInstalled()){
        Log.d("weixinPay","未安装微信");
        return;
        }
        if(!ApplicationXpClient.MSGAPI.isWXAppSupportAPI()){
        Log.d("weixinPay","版本不支持");
        return;
        }
        PayReq request=new PayReq();//weixinPayData是后台返回的类
        request.appId=ApplicationXpClient.WX_APPID;
        request.partnerId="1387300802";
        request.prepayId=weixinPayData.getPrepay_id();
        request.packageValue="Sign=WXPay";
        request.nonceStr=weixinPayData.getNonce_str();
        request.timeStamp=weixinPayData.getDateTime();
        request.sign=weixinPayData.getSign();
        ApplicationXpClient.MSGAPI.sendReq(request);

分享功能

        int WX_THUMB_SIZE=120;
        if(!ApplicationXpClient.MSGAPI.isWXAppInstalled()){
        Log.d("weixinPay","未安装微信");
        return;
        }
        if(!ApplicationXpClient.MSGAPI.isWXAppSupportAPI()){
        Log.d("weixinPay","版本不支持");
        return;
        }
        //初始化一个WXWebpageObject对象,填写url
        WXWebpageObject webpage=new WXWebpageObject();
 
        webpage.webpageUrl="www.pooai.com";//这里用小普马桶官网做推广
 
        //用WXWebpageObject对象初始化一个WXMediaMessage对象,填写标题、描述
        WXMediaMessage msg=new WXMediaMessage(webpage);
        msg.title="小普未来科技";
        msg.description="一款来自未来的云健康智能马桶";
        Bitmap thumb=BitmapFactory.decodeResource(getResources(),R.drawable.xiaopu);
        Bitmap thumbBmp=Bitmap.createScaledBitmap(thumb,WX_THUMB_SIZE,WX_THUMB_SIZE,true);
        thumb.recycle();
        msg.thumbData=bmpToByteArray(thumbBmp,true);
 
        //构造一个Req
        SendMessageToWX.Req req=new SendMessageToWX.Req();
        req.transaction=String.valueOf(System.currentTimeMillis());
        req.message=msg;
        req.scene=SendMessageToWX.Req.WXSceneSession;//分享给朋友
        //req.scene = SendMessageToWX.Req.WXSceneTimeline;//分享到朋友圈
        ApplicationXpClient.MSGAPI.sendReq(req);
 
  public static byte[]bmpToByteArray(final Bitmap bmp,final boolean needRecycle){
        ByteArrayOutputStream output=new ByteArrayOutputStream();
        bmp.compress(CompressFormat.PNG,100,output);
        if(needRecycle){
        bmp.recycle();
        }
        byte[]result=output.toByteArray();
        try{
        output.close();
        }catch(Exception e){
        e.printStackTrace();
        }
        return result;
        }

你可能感兴趣的:(Android)