您的位置:首页 > 移动开发 > 微信开发

salesforce 和微信的集成(一)通过SFDC Site打开微信开发接口

2014-11-04 09:51 399 查看
本文代码参照柳峰的代码。十分感谢。

开始在做微信集成的时候,是采用微信+阿里云服务器+SFDC这种模式进行的。在阿里云上部署java程序实现和微信服务器的沟通,在通过SFDC的对外API实现和java程序的沟通。这种方式使项目成本提升,并且大多数客户难以接受。

后来在论坛和qq群里,看大家的讨论,发现可以采用REST API来实现。在我的传统观念里REST API需要使用SeessionID和token的。使用site功能,就相当于把借口直接暴露出来,省去了Oath认证的步骤,一般在做接口测试的时候会这么做。(Site这个功能,在有的org里没有,需要申请,这部分内容我不打了解。不过我申请的免费开发org里有这个功能)

闲言不多说。

1、在SFDC上创建Site,设置如图。



2、点击保存按钮进入到如图的页面(下次进来的时候,要先edit,然后保存,才能再次来到这个页面)



在标示为1的地方设计Site访问的class,和profile的设置方法类似。标记为2的地方不可以添加任何的页面,否则程序出现问题。

3、新建一个类代码如下

@RestResource(urlMapping='/CoreService/*')
global with sharing class ApexRESTCycleExample {
@HttpGet
global static void doGet(){
// 微信加密签名
String signature=RestContext.request.params.get('signature');
// 时间戳
String timestamp=RestContext.request.params.get('timestamp');
// 随机数
String nonce=RestContext.request.params.get('nonce');
// 随机字符串
String echostr=RestContext.request.params.get('echostr');
system.debug(signature+'====='+timestamp+'====='+nonce+'====');
String endstr= '';
if(checkSignature(signature,timestamp,nonce)){

RestContext.response.addHeader('Content-Type', 'text/plain');
RestContext.response.responseBody = Blob.valueOf(echostr);

}
}
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[] { 'weixin', timestamp, nonce };
// 将token、timestamp、nonce三个参数进行字典序排序
// Arrays.sort(arr);
arr.sort();
String content = '';
for (Integer i = 0; i < arr.size(); i++) {
content += arr[i];
}
Blob hash = Crypto.generateDigest('SHA1',Blob.valueOf(content));
String hexDigest = EncodingUtil.convertToHex(hash);
String singUpperCase = hexDigest.toUpperCase();
System.debug(singUpperCase +'===============');

// 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
Boolean flag = singUpperCase != null ? singUpperCase .equals(signature.toUpperCase()) : false;
system.debug(flag + '==============');
return flag;

}

}


该段代码参考柳峰的博客编写。

4、测试程序如图。注意:必须以https的形式访问,否则失败





5、设置微信中的接口

复制上面的link到微信里,就可以成功打开了。

问题总结:1、我在写的时候,由于不知道可以直接调用API返回数据,绕了很多的弯路。

2、要以https的方式请求。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐