monotouch 微信第三方开发

官方文档:

https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&lang=zh_CN&target=res/app_wx_powered_interface


创建binding项目  objective sharpie生成映射文件

StructsAndEnums文件

public    enum  WXErrCode {

        WXSuccess           = 0,
        WXErrCodeCommon     = -1,
        WXErrCodeUserCancel = -2,
        WXErrCodeSentFail   = -3,
        WXErrCodeAuthDeny   = -4,
        WXErrCodeUnsupport  = -5,
    };

    public enum WXScene {

        WXSceneSession  = 0, 
        WXSceneTimeline = 1,
        WXSceneFavorite = 2,
    };

    public    enum WXAPISupport {

        WXAPISupportSession = 0,
    };


ApiDefinition文件

// @interface BaseReq : NSObject
    [BaseType (typeof(NSObject))]
    interface BaseReq
    {
        // @property (assign, nonatomic) int type;
        [Export ("type")]
        int Type { get; set; }

        // @property (retain, nonatomic) NSstring * openID;
        [Export ("openID", ArgumentSemantic.Retain)]
        string OpenID { get; set; }
    }

    // @interface BaseResp : NSObject
    [BaseType (typeof(NSObject))]
    interface BaseResp
    {
        // @property (assign, nonatomic) int errCode;
        [Export ("errCode")]
        int ErrCode { get; set; }

        // @property (retain, nonatomic) NSstring * errStr;
        [Export ("errStr", ArgumentSemantic.Retain)]
        string ErrStr { get; set; }

        // @property (assign, nonatomic) int type;
        [Export ("type")]
        int Type { get; set; }
    }

    // @interface PayReq : BaseReq
    [BaseType (typeof(BaseReq))]
    interface PayReq
    {
        // @property (retain, nonatomic) NSstring * partnerId;
        [Export ("partnerId", ArgumentSemantic.Retain)]
        string PartnerId { get; set; }

        // @property (retain, nonatomic) NSstring * prepayId;
        [Export ("prepayId", ArgumentSemantic.Retain)]
        string PrepayId { get; set; }

        // @property (retain, nonatomic) NSstring * nonceStr;
        [Export ("nonceStr", ArgumentSemantic.Retain)]
        string NonceStr { get; set; }

        // @property (assign, nonatomic) UInt32 timeStamp;
        [Export ("timeStamp")]
        uint TimeStamp { get; set; }

        // @property (retain, nonatomic) NSstring * package;
        [Export ("package", ArgumentSemantic.Retain)]
        string Package { get; set; }

        // @property (retain, nonatomic) NSstring * sign;
        [Export ("sign", ArgumentSemantic.Retain)]
        string Sign { get; set; }
    }

    // @interface PayResp : BaseResp
    [BaseType (typeof(BaseResp))]
    interface PayResp
    {
        // @property (retain, nonatomic) NSstring * returnKey;
        [Export ("returnKey", ArgumentSemantic.Retain)]
        string ReturnKey { get; set; }
    }

    // @interface SendAuthReq : BaseReq
    [BaseType (typeof(BaseReq))]
    interface SendAuthReq
    {
        // @property (retain, nonatomic) NSstring * scope;
        [Export ("scope", ArgumentSemantic.Retain)]
        string Scope { get; set; }

        // @property (retain, nonatomic) NSstring * state;
        [Export ("state", ArgumentSemantic.Retain)]
        string State { get; set; }
    }

    // @interface SendAuthResp : BaseResp
    [BaseType (typeof(BaseResp))]
    interface SendAuthResp
    {
        // @property (retain, nonatomic) NSstring * code;
        [Export ("code", ArgumentSemantic.Retain)]
        string Code { get; set; }

        // @property (retain, nonatomic) NSstring * state;
        [Export ("state", ArgumentSemantic.Retain)]
        string State { get; set; }

        // @property (retain, nonatomic) NSstring * lang;
        [Export ("lang", ArgumentSemantic.Retain)]
        string Lang { get; set; }

        // @property (retain, nonatomic) NSstring * country;
        [Export ("country", ArgumentSemantic.Retain)]
        string Country { get; set; }
    }

    // @interface SendMessageToWXReq : BaseReq
    [BaseType (typeof(BaseReq))]
    interface SendMessageToWXReq
    {
        // @property (retain, nonatomic) NSstring * text;
        [Export ("text", ArgumentSemantic.Retain)]
        string Text { get; set; }

        // @property (retain, nonatomic) WXMediaMessage * message;
        [Export ("message", ArgumentSemantic.Retain)]
        WXMediaMessage Message { get; set; }

        // @property (assign, nonatomic) BOOL bText;
        [Export ("bText")]
        bool BText { get; set; }

        // @property (assign, nonatomic) int scene;
        [Export ("scene")]
        int Scene { get; set; }
    }

    // @interface SendMessageToWXResp : BaseResp
    [BaseType (typeof(BaseResp))]
    interface SendMessageToWXResp
    {
        // @property (retain, nonatomic) NSstring * lang;
        [Export ("lang", ArgumentSemantic.Retain)]
        string Lang { get; set; }

        // @property (retain, nonatomic) NSstring * country;
        [Export ("country", ArgumentSemantic.Retain)]
        string Country { get; set; }
    }

    // @interface GetMessageFromWXReq : BaseReq
    [BaseType (typeof(BaseReq))]
    interface GetMessageFromWXReq
    {
        // @property (retain, nonatomic) NSstring * lang;
        [Export ("lang", ArgumentSemantic.Retain)]
        string Lang { get; set; }

        // @property (retain, nonatomic) NSstring * country;
        [Export ("country", ArgumentSemantic.Retain)]
        string Country { get; set; }
    }

    // @interface GetMessageFromWXResp : BaseResp
    [BaseType (typeof(BaseResp))]
    interface GetMessageFromWXResp
    {
        // @property (retain, nonatomic) NSstring * text;
        [Export ("text", ArgumentSemantic.Retain)]
        string Text { get; set; }

        // @property (retain, nonatomic) WXMediaMessage * message;
        [Export ("message", ArgumentSemantic.Retain)]
        WXMediaMessage Message { get; set; }

        // @property (assign, nonatomic) BOOL bText;
        [Export ("bText")]
        bool BText { get; set; }
    }

    // @interface ShowMessageFromWXReq : BaseReq
    [BaseType (typeof(BaseReq))]
    interface ShowMessageFromWXReq
    {
        // @property (retain, nonatomic) WXMediaMessage * message;
        [Export ("message", ArgumentSemantic.Retain)]
        WXMediaMessage Message { get; set; }

        // @property (retain, nonatomic) NSstring * lang;
        [Export ("lang", ArgumentSemantic.Retain)]
        string Lang { get; set; }

        // @property (retain, nonatomic) NSstring * country;
        [Export ("country", ArgumentSemantic.Retain)]
        string Country { get; set; }
    }

    // @interface ShowMessageFromWXResp : BaseResp
    [BaseType (typeof(BaseResp))]
    interface ShowMessageFromWXResp
    {
    }

    // @interface LaunchFromWXReq : BaseReq
    [BaseType (typeof(BaseReq))]
    interface LaunchFromWXReq
    {
        // @property (retain, nonatomic) WXMediaMessage * message;
        [Export ("message", ArgumentSemantic.Retain)]
        WXMediaMessage Message { get; set; }

        // @property (retain, nonatomic) NSstring * lang;
        [Export ("lang", ArgumentSemantic.Retain)]
        string Lang { get; set; }

        // @property (retain, nonatomic) NSstring * country;
        [Export ("country", ArgumentSemantic.Retain)]
        string Country { get; set; }
    }

    // @interface WXMediaMessage : NSObject
    [BaseType (typeof(NSObject))]
    interface WXMediaMessage
    {
        // +(WXMediaMessage *)message;
        [Static]
        [Export ("message")]
        WXMediaMessage Message { get; }

        // @property (retain, nonatomic) NSstring * titleWXApiDelegateWXApiDelegate;
        [Export ("title", ArgumentSemantic.Retain)]
        string Title { get; set; }

        // @property (retain, nonatomic) NSstring * description;
        [Export ("description", ArgumentSemantic.Retain)]
        string Description { get; set; }

        // @property (retain, nonatomic) NSData * thumbData;
        [Export ("thumbData", ArgumentSemantic.Retain)]
        NSData ThumbData { get; set; }

        // @property (retain, nonatomic) NSstring * mediaTagName;
        [Export ("mediaTagName", ArgumentSemantic.Retain)]
        string MediaTagName { get; set; }

        // @property (retain, nonatomic) NSstring * messageExt;
        [Export ("messageExt", ArgumentSemantic.Retain)]
        string MessageExt { get; set; }

        // @property (retain, nonatomic) NSstring * messageAction;
        [Export ("messageAction", ArgumentSemantic.Retain)]
        string MessageAction { get; set; }

        // @property (retain, nonatomic) id mediaObject;
        [Export ("mediaObject", ArgumentSemantic.Retain)]
        NSObject MediaObject { get; set; }

        [Export("setThumbImage:")]
        void SetThumbImage (UIImage image); 
    }

    // @interface WXImageObject : NSObject
    [BaseType (typeof(NSObject))]
    interface WXImageObject
    {
        // +(WXImageObject *)object;
        [Static]
        [Export ("object")]

        WXImageObject Object { get; }

        // @property (retain, nonatomic) NSData * imageData;
        [Export ("imageData", ArgumentSemantic.Retain)]
        NSData ImageData { get; set; }

        // @property (retain, nonatomic) NSstring * imageUrl;
        [Export ("imageUrl", ArgumentSemantic.Retain)]
        string ImageUrl { get; set; }
    }

    // @interface WXMusicObject : NSObject
    [BaseType (typeof(NSObject))]
    interface WXMusicObject
    {
        // +(WXMusicObject *)object;
        [Static]
        [Export ("object")]

        WXMusicObject Object { get; }

        // @property (retain, nonatomic) NSstring * musicUrl;
        [Export ("musicUrl", ArgumentSemantic.Retain)]
        string MusicUrl { get; set; }

        // @property (retain, nonatomic) NSstring * musicLowBandUrl;
        [Export ("musicLowBandUrl", ArgumentSemantic.Retain)]
        string MusicLowBandUrl { get; set; }

        // @property (retain, nonatomic) NSstring * musicDataUrl;
        [Export ("musicDataUrl", ArgumentSemantic.Retain)]
        string MusicDataUrl { get; set; }

        // @property (retain, nonatomic) NSstring * musicLowBandDataUrl;
        [Export ("musicLowBandDataUrl", ArgumentSemantic.Retain)]
        string MusicLowBandDataUrl { get; set; }
    }

    // @interface WXVideoObject : NSObject
    [BaseType (typeof(NSObject))]
    interface WXVideoObject
    {
        // +(WXVideoObject *)object;
        [Static]
        [Export ("object")]

        WXVideoObject Object { get; }

        // @property (retain, nonatomic) NSstring * videoUrl;
        [Export ("videoUrl", ArgumentSemantic.Retain)]
        string VideoUrl { get; set; }

        // @property (retain, nonatomic) NSstring * videoLowBandUrl;
        [Export ("videoLowBandUrl", ArgumentSemantic.Retain)]
        string VideoLowBandUrl { get; set; }
    }

    // @interface WXWebpageObject : NSObject
    [BaseType (typeof(NSObject))]
    interface WXWebpageObject
    {
        // +(WXWebpageObject *)object;
        [Static]
        [Export ("object")]

        WXWebpageObject Object { get; }

        // @property (retain, nonatomic) NSstring * webpageUrl;
        [Export ("webpageUrl", ArgumentSemantic.Retain)]
        string WebpageUrl { get; set; }
    }

    // @interface WXAppExtendObject : NSObject
    [BaseType (typeof(NSObject))]
    interface WXAppExtendObject
    {
        // +(WXAppExtendObject *)object;
        [Static]
        [Export ("object")]

        WXAppExtendObject Object { get; }

        // @property (retain, nonatomic) NSstring * url;
        [Export ("url", ArgumentSemantic.Retain)]
        string Url { get; set; }

        // @property (retain, nonatomic) NSstring * extInfo;
        [Export ("extInfo", ArgumentSemantic.Retain)]
        string ExtInfo { get; set; }

        // @property (retain, nonatomic) NSData * fileData;
        [Export ("fileData", ArgumentSemantic.Retain)]
        NSData FileData { get; set; }
    }

    // @interface WXEmoticonObject : NSObject
    [BaseType (typeof(NSObject))]
    interface WXEmoticonObject
    {
        // +(WXEmoticonObject *)object;
        [Static]
        [Export ("object")]

        WXEmoticonObject Object { get; }

        // @property (retain, nonatomic) NSData * emoticonData;
        [Export ("emoticonData", ArgumentSemantic.Retain)]
        NSData EmoticonData { get; set; }
    }

    // @interface WXFileObject : NSObject
    [BaseType (typeof(NSObject))]
    interface WXFileObject
    {
        // +(WXFileObject *)object;
        [Static]
        [Export ("object")]

        WXFileObject Object { get; }

        // @property (retain, nonatomic) NSstring * fileExtension;
        [Export ("fileExtension", ArgumentSemantic.Retain)]
        string FileExtension { get; set; }

        // @property (retain, nonatomic) NSData * fileData;
        [Export ("fileData", ArgumentSemantic.Retain)]
        NSData FileData { get; set; }
    }

    // @protocol WXApiDelegate <NSObject>
    [Protocol,Model]
    [BaseType (typeof(UIApplicationDelegate))]
    interface WXApiDelegate
    {
        // @optional -(void)onReq:(BaseReq *)req;
        [Export ("onReq:")]
        void OnReq (BaseReq req);

        // @optional -(void)onResp:(BaseResp *)resp;
        [Export ("onResp:")]
        void OnResp (BaseResp resp);
    }

    // @interface WXApi : NSObject
    [BaseType (typeof(NSObject))]
    interface WXApi
    {
        // +(BOOL)registerApp:(NSstring *)appid;
        [Static]
        [Export ("registerApp:")]
        bool RegisterApp (string appid);

        // +(BOOL)registerApp:(NSstring *)appid withDescription:(NSstring *)appdesc;
        [Static]
        [Export ("registerApp:withDescription:")]
        bool RegisterApp (string appid, string appdesc);

        // +(BOOL)handleOpenURL:(NSURL *)url delegate:(id<WXApiDelegate>)delegate;
        [Static]
        [Export ("handleOpenURL:delegate:")]
        bool HandleOpenURL (NSUrl url, WXApiDelegate delegt);

        // +(BOOL)isWXAppInstalled;
        [Static]
        [Export ("isWXAppInstalled")]

        bool IsWXAppInstalled { get; }

        // +(BOOL)isWXAppSupportApi;
        [Static]
        [Export ("isWXAppSupportApi")]

        bool IsWXAppSupportApi { get; }

        // +(NSstring *)getWXAppInstallUrl;
        [Static]
        [Export ("getWXAppInstallUrl")]

        string WXAppInstallUrl { get; }

        // +(NSstring *)getApiVersion;
        [Static]
        [Export ("getApiVersion")]

        string ApiVersion { get; }

        // +(BOOL)openWXApp;
        [Static]
        [Export ("openWXApp")]

        bool OpenWXApp { get; }

        // +(BOOL)sendReq:(BaseReq *)req;
        [Static]
        [Export ("sendReq:")]
        bool SendReq (BaseReq req);

        // +(BOOL)sendResp:(BaseResp *)resp;
        [Static]
        [Export ("sendResp:")]
        bool SendResp (BaseResp resp);

        // +(BOOL)safeSendReq:(BaseReq *)req;
        [Static]
        [Export ("safeSendReq:")]
        bool SafeSendReq (BaseReq req);
    }

OnReq:本机向微信发送请求

OnResp:微信向本机发送的请求

授权代码

void SendAuthToWX()
{
            if (WXApi.IsWXAppInstalled) {
                SendAuthReq req = new SendAuthReq ();
                req.Scope = "snsapi_userinfo" ;
                req.State = "com.aggior.litebreeze" ;
                WXApi.SendReq (req);
            }
}

通过code获取accesstoken

void GetAccessTokenWithCode(string code)
        {
            /*
                 正确返回
                         "access_token" = “Oez*****8Q";
                         "expires_in" = 7200;
                         openid = ooVLKjppt7****p5cI;
                         "refresh_token" = “Oez*****smAM-g";
                         scope = "snsapi_userinfo";

                错误返回
                        errcode = 40029;
                        errmsg = "invalid code";
             */

            string url =String.Format ("{0}/sns/oauth2/access_token?appid={1}&secret={2}&code={3}&grant_type=authorization_code",wechatbaseurl,appId,appsecret,code);
            this.BeginInvokeOnMainThread ((new Action(()=>{
                string dataStr = new WebClient().DownloadString(url);
                NSData data=NSData.FromString(dataStr);
                NSError error=null;
                var dic = (NSDictionary)NSJsonSerialization.Deserialize(data,NSJsonReadingOptions.MutableContainers,out error);
                if(dic.ObjectForKey(new NSString("errcode"))!=null)
                {
                    NSString errcode=(NSString)dic.ObjectForKey(new NSString("errcode"));
                    NSString errmsg=(NSString)dic.ObjectForKey(new NSString("errmsg"));
                    Console.WriteLine("[GetAccessTokenWithCode]"+errcode.ToString()+errmsg.ToString());
                }
                else
                {
                    NSString token=(NSString)dic.ObjectForKey(new NSString("accessToken"));
                    NSUserDefaults.StandardUserDefaults.SetString(token.ToString(),"accessToken");
                    NSString refreshToken=(NSString)dic.ObjectForKey(new NSString("refreshToken"));
                    NSUserDefaults.StandardUserDefaults.SetString(refreshToken.ToString(),"refreshToken");
                    NSString openid=(NSString)dic.ObjectForKey(new NSString("openID"));
                    NSUserDefaults.StandardUserDefaults.SetString(openid.ToString(),"openID");
                    GetUserInfoWithAccessToken(token.ToString(),openid.ToString());
                }


            })));
        
        }

通过token openID获取微信用户信息
    void GetUserInfoWithAccessToken(string token,string openid)
    {
            /*
             成功返回
             { 
                "openid":"OPENID",
                "nickname":"NICKNAME",
                "sex":1,
                "province":"PROVINCE",
                "city":"CITY",
                "country":"COUNTRY",
                "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
                "privilege":[
                "PRIVILEGE1", 
                "PRIVILEGE2"
                ],
                "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"

            }

            错误代码
            errcode = 42001;
            errmsg = "access_token expired";
            */
        string urlStr = String.Format ("{0}/userinfo?access_token={1}&openid={2}",wechatbaseurl,token,openid);
        NSUrl url=new NSUrl(urlStr);
        this.BeginInvokeOnMainThread (new Action(()=>
        {
            string dataStr = new WebClient().DownloadString(urlStr);
            NSData data=NSData.FromString(dataStr);
            NSError error=null;
            var dic = (NSDictionary)NSJsonSerialization.Deserialize(data,NSJsonReadingOptions.MutableContainers,out error);
            if(dic.ObjectForKey(new NSString("errcode"))!=null)
            {
                NSString errcode=(NSString)dic.ObjectForKey(new NSString("errcode"));
                NSString errmsg=(NSString)dic.ObjectForKey(new NSString("errmsg"));
                Console.WriteLine("[GetUserInfoWithAccessToken]"+errcode.ToString()+errmsg.ToString());

                string refreshToken = NSUserDefaults.StandardUserDefaults.StringForKey("refresToken");
                GetAccessTokenWithRefreshToken(refreshToken);
            }
            else
            {
                //获取数据
            }
        }));
    }

通过refreshtoken刷新token
    void GetAccessTokenWithRefreshToken(string refreshToken)
    {
            string urlStr = String.Format ("{0}/oauth2/refresh_token?appid={1}&grant_type=refresh_token&refresh_token={2}",wechatbaseurl,appId,refreshToken);
        this.BeginInvokeOnMainThread(new Action(()=>{
            string dataStr = new WebClient().DownloadString(urlStr);
            NSData data=NSData.FromString(dataStr);
            NSError error=null;
            var dic = (NSDictionary)NSJsonSerialization.Deserialize(data,NSJsonReadingOptions.MutableContainers,out error);
            if(dic.ObjectForKey(new NSString("errcode"))!=null)
            {
                NSString errcode=(NSString)dic.ObjectForKey(new NSString("errcode"));
                NSString errmsg=(NSString)dic.ObjectForKey(new NSString("errmsg"));
                Console.WriteLine("[GetAccessTokenWithRefreshToken]"+errcode.ToString()+errmsg.ToString());
            }
            else
            {
                NSString newToken=(NSString)dic.ObjectForKey(new NSString("accessToken"));
                NSUserDefaults.StandardUserDefaults.SetString(newToken.ToString(),"accessToken");
                NSString newRefreshToken=(NSString)dic.ObjectForKey(new NSString("refreshToken"));
                NSUserDefaults.StandardUserDefaults.SetString(newRefreshToken.ToString(),"refreshToken");
                NSString newOpenID=(NSString)dic.ObjectForKey(new NSString("openID"));
                NSUserDefaults.StandardUserDefaults.SetString(newOpenID.ToString(),"openID");
            }
        }));


    }

你可能感兴趣的:(monotouch 微信第三方开发)